using GadgetCore.API;
using HarmonyLib;
using System.Collections;
using UnityEngine;

namespace LoopPortal.Patches
{

  [HarmonyPatch(typeof(EntranceScript))]
  [HarmonyPatch("SpawnEndPortal")]
  [HarmonyGadget("LoopPortal")]
  public static class Patch_EntranceScript_SpawnEndPortal
  {
    [HarmonyPostfix]
    public static void Postfix(EntranceScript __instance)
    {
      __instance.StartCoroutine(AddPortal(__instance));
    }

    public static IEnumerator AddPortal(EntranceScript __instance)
    {
      yield return new WaitForSeconds(0.1f);
      if (GameScript.endPortal[0] != null && Network.isServer)
      {

        var spawnSpot = __instance.spawnSpot;

        var i = (GameObject)Network.Instantiate((GameObject)Resources.Load("portal"), new Vector3(spawnSpot[0].transform.position.x - 7.5f, spawnSpot[0].transform.position.y + 1.2f, 0f), Quaternion.identity, 0);
        i.name = "portal/4/obj";
        var iUA = i.transform.GetChild(0).gameObject;
        i.GetComponent<NetworkView>().RPC("Activate", RPCMode.All, new object[0]);
        iUA.GetComponent<NetworkView>().RPC("Set", RPCMode.AllBuffered, new object[] { SpawnerScript.curBiome, 0, 4 });
        Core.portalObject = i;
      }
      yield break;
    }
  }
}
