using System;
using BepInEx.Configuration;
using HarmonyLib;

namespace TerraTech {
    [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 readonly MultipliedObjectManager<Projectile> projectileManager =
            new MultipliedObjectManager<Projectile>(ConfigureProjectile);
        private static readonly MultipliedObjectManager<MissileProjectile> missileProjectileManager =
            new MultipliedObjectManager<MissileProjectile>(ConfigureMissileProjectile);

        public static ConfigEntry<bool> playerOnly;
        public static ConfigEntry<float> kickbackStrengthMultiplier;
        public static ConfigEntry<float> muzzleVelocityMultiplier;
        public static ConfigEntry<float> burstCooldownMultiplier;
        public static ConfigEntry<float> burstShotCountMultiplier;
        public static ConfigEntry<float> shotCooldownMultiplier;
        public static ConfigEntry<bool> seekingRoundsAll;
        public static ConfigEntry<bool> resetBurstOnInterruptAll;
        public static ConfigEntry<float> projectileLifetimeMultiplier;
        public static ConfigEntry<float> missileProjectileBoosterLifetimeMultiplier;
        public static ConfigEntry<bool> projectileExplodeOnStickAll;

        public static void Setup(ConfigFile config) {
            float min = 0.01f;
            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();

            projectileLifetimeMultiplier = config.Bind(
                "Projectile", "Lifetime Multiplier", 1f,
                new ConfigDescription("Projectile Lifetime Multiplier", new AcceptableValueRange<float>(min, max)));
            projectileLifetimeMultiplier.SettingChanged += (sender, args) => DoPatch();

            missileProjectileBoosterLifetimeMultiplier =
                config.Bind("MissileProjectile", "Booster Lifetime Multiplier", 1f,
                            new ConfigDescription("Missile Projectile Booster Lifetime Multiplier",
                                                  new AcceptableValueRange<float>(min, max)));
            missileProjectileBoosterLifetimeMultiplier.SettingChanged += (sender, args) => DoPatch();

            projectileExplodeOnStickAll = config.Bind(
                "Projectile", "Explode On Stick All", false,
                new ConfigDescription("Projectile Explode On Stick All", new AcceptableValueRange<bool>(false, true)));
            projectileExplodeOnStickAll.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 void ConfigureProjectile(MultipliedObject<Projectile> obj) {
            obj.AddField(new FieldConfiguration<float, float>("m_Lifetime", projectileLifetimeMultiplier));
            obj.AddField(new FieldConfiguration<bool, bool>("m_ExplodeOnStick", projectileExplodeOnStickAll));
        }

        private static void ConfigureMissileProjectile(MultipliedObject<MissileProjectile> obj) {
            obj.AddField(new FieldConfiguration<float, float>("m_MaxBoosterLifetime",
                                                              missileProjectileBoosterLifetimeMultiplier));
        }

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

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ModuleWeaponGun), "OnAttached")]
        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");
            var projectile = trav.Field("m_BulletPrefab");
            var projectileType = projectile.GetValueType();
            var isMissileProjectile = projectileType == typeof(MissileProjectile);

            fireDataManager.OnObjectAttached(firingData.GetValue<FireData>());
            if (isMissileProjectile) {
                var mproj = projectile.GetValue<MissileProjectile>();
                if (mproj != null)
                    missileProjectileManager.OnObjectAttached(mproj);
            } else {
                var proj = projectile.GetValue<Projectile>();
                if (proj != null)
                    projectileManager.OnObjectAttached(proj);
            }
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ModuleWeaponGun), "OnDetaching")]
        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");
            var projectile = trav.Field("m_BulletPrefab");
            var projectileType = projectile.GetValueType();
            var isMissileProjectile = projectileType == typeof(MissileProjectile);

            fireDataManager.OnObjectDetached(firingData.GetValue<FireData>());
            manager.OnObjectDetached(__instance);
            if (isMissileProjectile) {
                var mproj = projectile.GetValue<MissileProjectile>();
                if (mproj != null)
                    missileProjectileManager.OnObjectDetached(mproj);
            } else {
                var proj = projectile.GetValue<Projectile>();
                if (proj != null)
                    projectileManager.OnObjectDetached(proj);
            }
        }

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