using GadgetCore.API;
using HarmonyLib;
using UnityEngine;

namespace Subworlds.Patches
{
  [HarmonyPatch(typeof(Chunk))]
  [HarmonyPatch("OnDestroy")]
  [HarmonyGadget("SubworldCore")]
  public static class Patch_Chunk_OnDestroyy
  {
    [HarmonyPrefix]
    [HarmonyPriority(1010)]
    public static void Prefix(Chunk __instance, ref GameObject[] ___networkStuff)
    {
      Core.shipPorterPlaced = false;
      Core.meteorPorterPlaced = false;

      if (GameScript.townBiome != Core.meteroidPlanet.GetID() && GameScript.townBiome != Core.shipPlanet.GetID())
        Core.lastBiome = GameScript.townBiome;

      if (___networkStuff.Length > 40)
      {
        if (Network.isServer)
        {
          for (int i = 0; i < ___networkStuff.Length; i++)
          {
            if (___networkStuff[i])
            {
              Network.RemoveRPCs(___networkStuff[i].GetComponent<NetworkView>().viewID);
              Network.Destroy(___networkStuff[i].gameObject);
            }
          }
        }
        ___networkStuff = new GameObject[40];
      }
    }
  }
}