using GadgetCore;
using GadgetCore.API;
using GadgetCore.Util;
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using UnityEngine;

namespace Subworlds.Patches
{

  [HarmonyPatch]
  [HarmonyGadget("SubworldCore_")]
  public static class Patch_SceneInjector_InjectIngame
  {

    [HarmonyTargetMethod]
    static MethodBase TargetMethod()
    {
      return AccessTools.Method(typeof(GadgetCoreAPI).Assembly.GetType("GadgetCore.SceneInjector"), "InjectIngame");
    }

    [HarmonyTranspiler]
    public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator gen)
    {
      var p = TranspilerHelper.CreateProcessor(instructions, gen);
      {
        var ilRefs = p.FindAllRefsByInsns(new List<CodeInstruction>(new CodeInstruction[] {
          new CodeInstruction(OpCodes.Ldloc_0)
        , new CodeInstruction(OpCodes.Ldc_I4_1)
        , new CodeInstruction(OpCodes.Sub)
        }));
        MethodInfo changeListMethod = typeof(Patch_SceneInjector_InjectIngame).GetMethod("ChangeList");
        foreach (var ilRef in ilRefs)
        {
          p.InjectHook(ilRef, changeListMethod);
        }
      }
      return p.Insns;
    }

    private static FieldInfo selectorPlanetsField = typeof(PlanetRegistry).GetField("selectorPlanets");
    private static FieldInfo planetButtonIconsField = typeof(PlanetRegistry).GetField("planetButtonIcons");

    public static void ChangeList()
    {
      List<PlanetInfo> list = Registry<PlanetRegistry, PlanetInfo, PlanetType>.Singleton.ToList<PlanetInfo>();
      foreach (var info in list)
        if (info.GetID() == Core.shipPlanet.GetID())
          list.Remove(info);
      selectorPlanetsField.SetValue(null, list.ToArray());
    }
  }
}