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

namespace ItemLevelExtension.Patches
{

  internal class MaxLevelGetter
  {
    public static int MaxLevel { get => Core.settingMaxItemLevel; }
  }

  [HarmonyPatch(typeof(PatchMethods))]
  [HarmonyPatch("HoverItem")]
  [HarmonyGadget("ItemLevelExtension")]
  public static class Patch_PatchMethods_HoverItem
  {
    [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, 10));
      MethodInfo getValue = typeof(MaxLevelGetter).GetProperty("MaxLevel").GetGetMethod();
      foreach (var ilRef in ilRefs)
      {
        //p.InjectInsn(ilRef, new CodeInstruction(OpCodes.Ldc_I4_S, 12), false);
        p.InjectInsn(ilRef, new CodeInstruction(OpCodes.Call, getValue), false);
      }
      return p.Insns;
    }
  }
}