using System;
using BepInEx.Configuration;
using HarmonyLib;

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

        public static ConfigEntry<bool> playerOnly;
        public static ConfigEntry<float> outputMultiplier;
        public 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), "OnAttached")]
        static void PostfixCreate(ModuleEnergy __instance) {
            manager.OnObjectAttached(__instance);
        }

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

        public static void DoPatch() {
            manager.ApplyAll();
        }
    }
}
