using System;
using System.Collections.Generic;
using BepInEx.Configuration;
using HarmonyLib;

namespace TerraTech {
    [HarmonyPatch]
    public class WeaponPropertiesManager {
        private static Dictionary<ModuleWeaponGun, float> shotCooldown = new Dictionary<ModuleWeaponGun, float>();

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ModuleWeaponGun), "OnAttached")]
        static void PostfixCreate(ModuleWeaponGun __instance) {
            // Console.WriteLine("ModuleWeaponGun.OnAttached");
            if (!shotCooldown.ContainsKey(__instance)) {
                shotCooldown.Add(__instance, __instance.m_ShotCooldown);
                // Console.WriteLine("Patching {0}; m_ShotCooldown: {1}", __instance.name, __instance.m_ShotCooldown);
                DoPatchSingle(__instance);
                // Console.WriteLine("Patched {0}; m_ShotCooldown: {1}", __instance.name, __instance.m_ShotCooldown);
            }
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ModuleWeaponGun), "OnDetaching")]
        static void PostfixDestroy(ModuleWeaponGun __instance) {
            // Console.WriteLine("ModuleWeaponGun.OnDetaching");
            // Console.WriteLine("Restoring {0}; m_ShotCooldown: {1}", __instance.name, __instance.m_ShotCooldown);
            DoRestoreSingle(__instance);
            // Console.WriteLine("Restored {0}; m_ShotCooldown: {1}", __instance.name, __instance.m_ShotCooldown);
            shotCooldown.Remove(__instance);
        }

        public static void DoPatch() {
            // Console.WriteLine("Modifying {0} ModuleWeaponGun", shotCooldown.Count);
            foreach (KeyValuePair<ModuleWeaponGun, float> keyValuePair in shotCooldown) {
                DoRestoreSingle(keyValuePair.Key);
                DoPatchSingle(keyValuePair.Key);
            }
        }

        static void DoPatchSingle(ModuleWeaponGun moduleWeaponGun) {
            moduleWeaponGun.m_ShotCooldown = shotCooldown[moduleWeaponGun] / Main.shootingSpeedMultiplier.Value;
        }

        static void DoRestoreSingle(ModuleWeaponGun moduleWeaponGun) {
            if (shotCooldown.ContainsKey(moduleWeaponGun)) {
                moduleWeaponGun.m_ShotCooldown = shotCooldown[moduleWeaponGun];
            }
        }
    }
}