using System;
using BepInEx.Configuration;
using HarmonyLib;

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

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

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

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