using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using HarmonyLib;

namespace DavesPhatStore {
	[HarmonyPatch]
	public class EmployeeBuffs {
		[HarmonyTranspiler]
		[HarmonyPatch(typeof(UpgradesManager), "ManageExtraPerks")]
		static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) {
			var codes = new List<CodeInstruction>(instructions);

			for (int i = 0; i < codes.Count; i++) {
				var codeInstruction = codes[i];
				// if (codeInstruction.operand != null) {
				// 	Console.WriteLine($"'{codeInstruction.operand.ToString()}'");
				// 	Console.WriteLine(codeInstruction.operand.ToString() == "NPC_Manager::extraEmployeeSpeedFactor");
				// }

				if (codeInstruction.opcode == OpCodes.Ldfld &&
				    codeInstruction.operand?.ToString() == "System.Int32 maxEmployees") {
					Console.WriteLine($"Found {codeInstruction.operand}");
					codes[i + 1].opcode = OpCodes.Nop;
					codes.Insert(i + 2,
						new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(Main), "employeePerPerk")));
					codes.Insert(i + 3,
						new CodeInstruction(OpCodes.Call,
							AccessTools.PropertyGetter(typeof(Main).GetField("employeePerPerk").FieldType, "Value")));
				}

				if (codeInstruction.opcode == OpCodes.Ldfld &&
				    codeInstruction.operand?.ToString() == "System.Single extraEmployeeSpeedFactor") {
					Console.WriteLine($"Found {codeInstruction.operand}");
					codes[i + 1].opcode = OpCodes.Nop;
					codes.Insert(i + 2,
						new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(Main), "employeeSpeedPerk")));
					codes.Insert(i + 3,
						new CodeInstruction(OpCodes.Call,
							AccessTools.PropertyGetter(typeof(Main).GetField("employeeSpeedPerk").FieldType, "Value")));
				}

				if (codeInstruction.opcode == OpCodes.Ldfld &&
				    codeInstruction.operand?.ToString() == "System.Single extraCheckoutMoney") {
					Console.WriteLine($"Found {codeInstruction.operand}");
					codes[i + 1].opcode = OpCodes.Nop;
					codes.Insert(i + 2,
						new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(Main), "employeeExtraMoneyPerk")));
					codes.Insert(i + 3,
						new CodeInstruction(OpCodes.Call,
							AccessTools.PropertyGetter(typeof(Main).GetField("employeeExtraMoneyPerk").FieldType,
								"Value")));
				}
			}

			return codes.AsEnumerable();
		}
	}
}