using GadgetCore.API;
using HarmonyLib;
using UnityEngine;

namespace Subworlds.Patches
{

  [HarmonyPatch(typeof(GameScript))]
  [HarmonyPatch("AddMod")]
  [HarmonyGadget("SubworldCore")]
	public static class Patch_GameScript_AddMod
	{

		[HarmonyPrefix]
    public static bool Prefix(GameScript __instance, int a, Item ___holdingItem, GameObject[] ___modObj, Item[] ___modSlot)
		{
			int n = 5;
			int id = ___modSlot[0].id;
			if (id > 0)
				for (int i = 0; i < 3; i++)
					if (___modSlot[0].aspect[i] > 0 && ___modSlot[0].aspect[i] == Core.itemOldTexMod.GetID())
						n += ___modSlot[0].aspectLvl[i];

			ItemInfo itemInfo = ItemRegistry.GetItem(___holdingItem.id);
			if ((___holdingItem.id > 200 && ___holdingItem.id < 230) || (itemInfo != null && ((itemInfo.Type & ItemType.MOD) == (ItemType.MOD))))
			{
				if (___modSlot[0].id != 0)
				{
					if (___modSlot[0].aspectLvl[a] < 5 || (___modSlot[0].aspectLvl[a] < n && ___holdingItem.id != Core.itemOldTexMod.GetID()))
					{
						if (___modSlot[0].aspect[a] == ___holdingItem.id || ___modSlot[0].aspect[a] == 0)
						{
							if (__instance.CanAddMod(a))
							{
								___modSlot[0].aspectLvl[a]++;
								___modObj[a].GetComponent<Animation>().Play();
								__instance.GetComponent<AudioSource>().PlayOneShot((AudioClip)Resources.Load("Au/addmod"), Menuu.soundLevel / 10f);
								___modSlot[0].aspect[a] = ___holdingItem.id;
								___holdingItem.q--;
								__instance.RefreshHoldingSlot();
								__instance.RefreshGearMods();
							}
						}
						else if (___modSlot[0].aspectLvl[a] == 0 && __instance.CanAddMod(a))
						{
							___modSlot[0].aspectLvl[a]++;
							___modObj[a].GetComponent<Animation>().Play();
							__instance.GetComponent<AudioSource>().PlayOneShot((AudioClip)Resources.Load("Au/addmod"), Menuu.soundLevel / 10f);
							___modSlot[0].aspect[a] = ___holdingItem.id;
							___holdingItem.q--;
							__instance.RefreshHoldingSlot();
							__instance.RefreshGearMods();
						}
					}
				}
			}
			return false;
		}
  }
}