using System;
using BepInEx.Configuration;
using HarmonyLib;

namespace BanquetForCyka {
    [HarmonyPatch]
    public class ModuleWeaponGunManager {
        private static readonly MultipliedObjectManager<ModuleWeaponGun> Manager =
            new MultipliedObjectManager<ModuleWeaponGun>(ConfigureManager);
        private static readonly MultipliedObjectManager<FireData> FireDataManager =
            new MultipliedObjectManager<FireData>(ConfigureFireData);

        private static ConfigEntry<bool> playerOnly;
        private static ConfigEntry<float> kickbackStrengthMultiplier;
        private static ConfigEntry<float> muzzleVelocityMultiplier;
        private static ConfigEntry<float> burstCooldownMultiplier;
        private static ConfigEntry<float> burstShotCountMultiplier;
        private static ConfigEntry<float> shotCooldownMultiplier;
        private static ConfigEntry<bool> seekingRoundsAll;
        private static ConfigEntry<bool> resetBurstOnInterruptAll;

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

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

            kickbackStrengthMultiplier = config.Bind(
                "FireData", "Kickback Strength Multiplier", 1f,
                new ConfigDescription("Kickback Strength Multiplier", new AcceptableValueRange<float>(min, max)));
            kickbackStrengthMultiplier.SettingChanged += (sender, args) => DoPatch();

            muzzleVelocityMultiplier = config.Bind(
                "FireData", "Muzzle Velocity Multiplier", 1f,
                new ConfigDescription("Muzzle Velocity Multiplier", new AcceptableValueRange<float>(min, max)));
            muzzleVelocityMultiplier.SettingChanged += (sender, args) => DoPatch();

            burstCooldownMultiplier = config.Bind(
                "FireData", "Burst Cooldown Multiplier", 1f,
                new ConfigDescription("Burst Cooldown Multiplier", new AcceptableValueRange<float>(min, max)));
            burstCooldownMultiplier.SettingChanged += (sender, args) => DoPatch();

            burstShotCountMultiplier = config.Bind(
                "FireData", "Burst Shot Count Multiplier", 1f,
                new ConfigDescription("Burst Shot Count Multiplier", new AcceptableValueRange<float>(min, max)));
            burstShotCountMultiplier.SettingChanged += (sender, args) => DoPatch();

            shotCooldownMultiplier = config.Bind(
                "FireData", "Shot Cooldown Multiplier", 1f,
                new ConfigDescription("Shot Cooldown Multiplier", new AcceptableValueRange<float>(min, max)));
            shotCooldownMultiplier.SettingChanged += (sender, args) => DoPatch();

            seekingRoundsAll =
                config.Bind("FireData", "Seeking Rounds All", false,
                            new ConfigDescription("Seeking Rounds All", new AcceptableValueRange<bool>(false, true)));
            seekingRoundsAll.SettingChanged += (sender, args) => DoPatch();

            resetBurstOnInterruptAll = config.Bind(
                "FireData", "Reset Burst On Interrupt All", false,
                new ConfigDescription("Reset Burst On Interrupt All", new AcceptableValueRange<bool>(false, true)));
            resetBurstOnInterruptAll.SettingChanged += (sender, args) => DoPatch();
        }

        private static void ConfigureManager(MultipliedObject<ModuleWeaponGun> obj) {
            obj.AddBooleanField(new BooleanFieldConfiguration("m_SeekingRounds", seekingRoundsAll, ShouldApply));
            obj.AddBooleanField(
                new BooleanFieldConfiguration("m_ResetBurstOnInterrupt", resetBurstOnInterruptAll, ShouldApply));
            obj.AddField(new FieldConfiguration<float, float>("m_BurstCooldown", burstCooldownMultiplier, ShouldApply));
            obj.AddField(new FieldConfiguration<int, float>("m_BurstShotCount", burstShotCountMultiplier, ShouldApply));
            obj.AddField(new FieldConfiguration<float, float>("m_ShotCooldown", shotCooldownMultiplier, ShouldApply));
        }

        private static void ConfigureFireData(MultipliedObject<FireData> obj) {
            obj.AddField(new FieldConfiguration<float, float>("m_MuzzleVelocity", muzzleVelocityMultiplier));
            obj.AddField(new FieldConfiguration<float, float>("m_KickbackStrength", kickbackStrengthMultiplier));
        }

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

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ModuleWeaponGun), "OnAttached")]
        public static void PostfixCreate(ModuleWeaponGun __instance) {
            Manager.OnObjectAttached(__instance);
            if (playerOnly.Value && !CykUtil.IsPlayerTank(__instance))
                return;

            var trav = Traverse.Create(__instance);
            var firingData = trav.Field("m_FiringData");
            FireDataManager.OnObjectAttached(firingData.GetValue<FireData>());
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ModuleWeaponGun), "OnDetaching")]
        public static void PostfixDestroy(ModuleWeaponGun __instance) {
            Manager.OnObjectAttached(__instance);
            var trav = Traverse.Create(__instance);
            if (playerOnly.Value && !CykUtil.IsPlayerTank(__instance))
                return;

            var firingData = trav.Field("m_FiringData");
            FireDataManager.OnObjectDetached(firingData.GetValue<FireData>());
        }

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

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