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

namespace StorageExpansion.Patches
{

  [HarmonyPatch()]
  [HarmonyGadget("StorageExpansion")]
  public static class RePatch_GameScript_Update
  {

    [HarmonyPrepare]
    static bool Prepare()
    {
      foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
      {
        if (a.FullName.StartsWith("QuickStack,"))
        {
          return true;
        }
      }
      return false;
    }

    [HarmonyTargetMethods]
    static IEnumerable<MethodBase> TargetMethods()
    {
      foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
      {
        if (a.FullName.StartsWith("QuickStack,"))
        {
          yield return AccessTools.Method(a.GetType("QuickStack.Patches.Patch_GameScript_Update"), "Prefix");
        }
      }
      yield break;
    }

    [HarmonyTranspiler]
    public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator gen)
    {
      var p = TranspilerHelper.CreateProcessor(instructions, gen);
      var ilRefs = p.FindAllRefsByInsn(new CodeInstruction(OpCodes.Ldc_I4_S, 30));
      MethodInfo getValue = typeof(SlotsPerPageGetter).GetProperty("SlotsPerPage").GetGetMethod();
      foreach (var ilRef in ilRefs)
      {
        p.InjectInsn(ilRef, new CodeInstruction(OpCodes.Call, getValue), false);
      }
      return p.Insns;
    }
  }
}