using System;
using BepInEx.Configuration;
using HarmonyLib;

namespace Ereshor {
    [HarmonyPatch]
    public class ModuleWeaponManager {
        private static readonly MultipliedObjectManager<ModuleWeapon> Manager =
            new MultipliedObjectManager<ModuleWeapon>(ConfigureManager);

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

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

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

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

        private static void ConfigureManager(MultipliedObject<ModuleWeapon> obj) {
            obj.AddField(new FieldConfiguration<float, float>("m_RotateSpeed", rotateSpeedMultiplier, ShouldApply));
        }

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

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

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