using System;
using BepInEx.Configuration;
using HarmonyLib;

namespace BlacksmithMaster {
    [HarmonyPatch]
    public class ModuleEnergyManager {
        private static readonly MultipliedObjectManager<ModuleEnergy> Manager =
            new MultipliedObjectManager<ModuleEnergy>(ConfigureModuleEnergy);

        private static ConfigEntry<bool> playerOnly;
        private static ConfigEntry<float> outputMultiplier;
        private static ConfigEntry<float> powerUpDelayMultiplier;

        public static void Setup(ConfigFile config) {
            float min = 0.01f;
            float max = 32f;

            playerOnly = config.Bind("Energy", "Player Only", false, new ConfigDescription("Player Only"));
            playerOnly.SettingChanged += (sender, args) => DoPatch();

            outputMultiplier =
                config.Bind("Energy", "Output Multiplier", 1f,
                            new ConfigDescription("Output Multiplier", new AcceptableValueRange<float>(min, max)));
            outputMultiplier.SettingChanged += (sender, args) => DoPatch();

            powerUpDelayMultiplier = config.Bind(
                "Energy", "Power Up Delay Multiplier", 1f,
                new ConfigDescription("Power Up Delay Multiplier", new AcceptableValueRange<float>(min, max)));
            powerUpDelayMultiplier.SettingChanged += (sender, args) => DoPatch();
        }

        private static void ConfigureModuleEnergy(MultipliedObject<ModuleEnergy> obj) {
            obj.AddField(new FieldConfiguration<float, float>("m_OutputPerSecond", outputMultiplier, ShouldApply));
            obj.AddField(new FieldConfiguration<float, float>("m_PowerUpDelay", powerUpDelayMultiplier, ShouldApply));
        }

        private static readonly Func<object, bool> ShouldApply = obj => {
            if (!playerOnly.Value)
                return true;
            return CykUtil.IsPlayerTank(obj as Module);
        };

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ModuleEnergy), "OnAnchorStatusChanged")]
        public static void PostfixCreate(ModuleEnergy __instance) {
            Manager.OnObjectAttached(__instance);
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ModuleEnergy), "OnDetaching")]
        public static void PostfixDestroy(ModuleEnergy __instance) {
            Manager.OnObjectDetached(__instance);
        }

        private static void DoPatch() {
            Manager.ApplyAll();
        }

        public static readonly Func<Module, bool> Register = obj => {
            if (Main.debug.Value)
                Console.WriteLine("Registering ModuleEnergy: {0}", obj);
            PostfixCreate(obj as ModuleEnergy);
            return true;
        };
    }
}
