using GadgetCore.API;
using HarmonyLib;
using UnityEngine;

namespace ScrapYard.Patches
{
  [HarmonyPatch(typeof(Chunk))]
  [HarmonyPatch("OnDestroy")]
  [HarmonyGadget("ScrapYard")]
  static class Patch_Chunk_OnDestroy
  {
    [HarmonyPrefix]
    public static void Prefix(ref GameObject[] ___networkStuff)
    {
      if (___networkStuff.Length > 40)
      {
        Core.logger.Log("Destroying large Planet");
        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];
      }
    }
  }
}