using System;
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;

namespace DavesPhatStore {
	[HarmonyPatch]
	public class WaitTimes : MonoBehaviour {
		public static List<WeakReference<NPC_Info>> NpcInfos = new List<WeakReference<NPC_Info>>();

		public void init() {
			InvokeRepeating(nameof(UpdateNpcs), 1f, 0.5f);
		}

		private static NPC_Info GetNpcInfo(int index) {
			if (index < 0 || index >= NpcInfos.Count)
				return null;

			NPC_Info npcInfo;
			if (NpcInfos[index].TryGetTarget(out npcInfo)) {
				return npcInfo;
			}

			return null;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(NPC_Info), MethodType.Constructor)]
		static void Postfix(NPC_Info __instance) {
			NpcInfos.Add(new WeakReference<NPC_Info>(__instance));
			// This does not work for some reason
			// I'm assuming times are updated by the game whenever the npc decides to do something
			// __instance.productItemPlaceWait = Main.productItemPlaceWait.Value;
			// __instance.productCheckoutWait = Main.productCheckoutWait.Value;
			// __instance.employeeItemPlaceWait = Main.employeeItemPlaceWait.Value;
			// Console.WriteLine(
			// 	$"Updated npc info with values: {__instance.productItemPlaceWait}, {__instance.productCheckoutWait}, {__instance.employeeItemPlaceWait}");
		}

		public void UpdateNpcs() {
			Main.productCheckoutWait.Value = Math.Max(Main.productCheckoutWait.Value, 0.02f);
			Main.productItemPlaceWait.Value = Math.Max(Main.productItemPlaceWait.Value, 0.02f);
			Main.employeeItemPlaceWait.Value = Math.Max(Main.employeeItemPlaceWait.Value, 0.02f);

			int n = 0;
			for (var i = 0; i < NpcInfos.Count; i++) {
				var npcInfo = GetNpcInfo(i);
				if (npcInfo == null) {
					NpcInfos.RemoveAt(i);
					i--;
					continue;
				}

				n++;
				npcInfo.productCheckoutWait = Main.productCheckoutWait.Value;
				npcInfo.productItemPlaceWait = Main.productItemPlaceWait.Value;
				npcInfo.employeeItemPlaceWait = Main.employeeItemPlaceWait.Value;
			}

			Console.WriteLine($"Updated {n} npc infos");
		}
	}
}