using System;
using BepInEx.Configuration;
using HarmonyLib;

namespace BlacksmithMaster {
    [HarmonyPatch]
    public class ModuleGyroManager {
        private static readonly MultipliedObjectManager<ModuleGyro> Manager =
            new MultipliedObjectManager<ModuleGyro>(ConfigureModuleGyro);

        private static ConfigEntry<bool> playerOnly;
        private static ConfigEntry<float> activeSpeedMultiplier;

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

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

            activeSpeedMultiplier = config.Bind(
                "Gyro", "Active Speed Multiplier", 1f,
                new ConfigDescription("Active Speed Multiplier", new AcceptableValueRange<float>(min, max)));
            activeSpeedMultiplier.SettingChanged += (sender, args) => DoPatch();
        }

        private static void ConfigureModuleGyro(MultipliedObject<ModuleGyro> obj) {
            obj.AddField(new FieldConfiguration<float, float>("m_ActiveSpeed", activeSpeedMultiplier, ShouldApply));
        }

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

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

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ModuleGyro), "OnDetaching")]
        public static void PostfixDestroy(ModuleGyro __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 ModuleGyro: {0}", obj);
            PostfixCreate(obj as ModuleGyro);
            return true;
        };
    }
}
