using GadgetCore.API;
using GadgetCore.Util;
using HarmonyLib;
using System.Collections;
using System.Threading;
using System.Windows.Threading;
using UnityEngine;

namespace Subworlds.Patches
{

  [HarmonyPatch(typeof(ObjectScript))]
  [HarmonyPatch("Die")]
  [HarmonyGadget("SubworldCore")]
  public static class Patch_ObjectScript_Die
  {
    [HarmonyPostfix]
    public static void Prefix(ObjectScript __instance, ref int ___id)
    {

      if (Network.isServer && Core.spawnObjects.Contains(___id))
      {
        if (Random.Range(0, 2) == 0)
          __instance.StartCoroutine(SpawnMultiple(__instance.transform.position.x + 2, __instance.transform.position.y, 2, 1 + Random.Range(0, 3), "e/Subworlds/BrokenSliver", 0.1f));
        else if (Random.Range(0, 12) == 0)
        {
          Item item = GadgetCoreAPI.EmptyItem();
          item.id = Core.itemOldTex.GetID();
          GadgetCoreAPI.SpawnItem(new Vector3(__instance.transform.position.x + 2, __instance.transform.position.y, 0.2f), item);
        }
      }
    }

    private static IEnumerator SpawnMultiple(float xBase, float yBase, float range, int amount, string name, float speed)
    {
      for (int i = 0; i < amount; i++)
      {
        int x = 0;
        int y = 0;
        if (range > 0)
        {
          x = Random.Range(-1 * (int)(range * 10), (int)(range * 10));
          y = Random.Range(-1 * (int)(range * 10), (int)(range * 10));
        }
        Network.Instantiate(Resources.Load(name), new Vector3(xBase + x / 10f, yBase + 1.1f + y / 10f, 0f), Quaternion.identity, 0);
        yield return new WaitForSeconds(speed);
      }
      yield break;
    }
  }
}