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

namespace TerraTech {
    [HarmonyPatch]
    public class FuelPropertiesManager {
        private static Dictionary<ModuleFuelTank, float> refillRate = new Dictionary<ModuleFuelTank, float>();
        private static Dictionary<ModuleFuelTank, float> capacity = new Dictionary<ModuleFuelTank, float>();

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ModuleFuelTank), "OnAttached")]
        static void PostfixCreate(ModuleFuelTank __instance) {
            // Console.WriteLine("ModuleFuelTank.OnAttached");
            if (!refillRate.ContainsKey(__instance)) {
                refillRate.Add(__instance, __instance.m_RefillRate);
                capacity.Add(__instance, __instance.m_Capacity);
                // Console.WriteLine("Patching {0}; m_RefillRate: {1}; m_Capacity: {2}", __instance.name, __instance.m_RefillRate, __instance.m_Capacity);
                DoPatchSingle(__instance);
                // Console.WriteLine("Patched {0}; m_RefillRate: {1}; m_Capacity: {2}", __instance.name, __instance.m_RefillRate, __instance.m_Capacity);
            }
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ModuleFuelTank), "OnDetaching")]
        static void PostfixDestroy(ModuleFuelTank __instance) {
            // Console.WriteLine("ModuleFuelTank.OnAttached");
            // Console.WriteLine("Restoring {0}; m_RefillRate: {1}; m_Capacity: {2}", __instance.name, __instance.m_RefillRate, __instance.m_Capacity);
            DoRestoreSingle(__instance);
            // Console.WriteLine("Restored {0}; m_RefillRate: {1}; m_Capacity: {2}", __instance.name, __instance.m_RefillRate, __instance.m_Capacity);
            refillRate.Remove(__instance);
            capacity.Remove(__instance);
        }

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

        static void DoPatchSingle(ModuleFuelTank moduleFuelTank) {
            moduleFuelTank.m_RefillRate = refillRate[moduleFuelTank] * Main.fuelTankRefillMultiplier.Value;
            moduleFuelTank.m_Capacity = capacity[moduleFuelTank] * Main.fuelTankCapacityMultiplier.Value;
        }

        static void DoRestoreSingle(ModuleFuelTank moduleFuelTank) {
            if (refillRate.ContainsKey(moduleFuelTank)) {
                moduleFuelTank.m_RefillRate = refillRate[moduleFuelTank];
                moduleFuelTank.m_Capacity = capacity[moduleFuelTank];
            }
        }
    }
}