using System;
using BepInEx.Configuration;
using HarmonyLib;

namespace BanquetForCyka {
    [HarmonyPatch]
    public class ModuleItemHolderManager {
        private static readonly MultipliedObjectManager<ModuleItemHolder> BeamManager =
            new MultipliedObjectManager<ModuleItemHolder>(ConfigureBeam);
        private static readonly MultipliedObjectManager<ModuleItemHolderBeam> BeamHolderManager =
            new MultipliedObjectManager<ModuleItemHolderBeam>(ConfigureBeamHolder);
        private static readonly MultipliedObjectManager<ModuleItemPickup> BeamPickupManager =
            new MultipliedObjectManager<ModuleItemPickup>(ConfigureBeamPickup);

        private static readonly MultipliedObjectManager<ModuleItemHolderMagnet> MagnetHolderManager =
            new MultipliedObjectManager<ModuleItemHolderMagnet>(ConfigureMagnetHolder);
        private static readonly MultipliedObjectManager<ModuleItemPickup> MagnetPickupManager =
            new MultipliedObjectManager<ModuleItemPickup>(ConfigureMagnetPickup);

        private static ConfigEntry<bool> playerOnly;
        private static ConfigEntry<float> capacityPerStackMultiplier;
        private static ConfigEntry<float> beamStrengthMultiplier;
        private static ConfigEntry<float> beamHeightIncrementScaleMultiplier;
        private static ConfigEntry<float> beamPickupRangeMultiplier;
        private static ConfigEntry<float> magnetStrengthMultiplier;
        private static ConfigEntry<float> magnetPickupRangeMultiplier;

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

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

            capacityPerStackMultiplier = config.Bind(
                "Item Holder", "Capacity Per Stack Multiplier", 1f,
                new ConfigDescription("Capacity Per Stack Multiplier", new AcceptableValueRange<float>(min, max)));
            capacityPerStackMultiplier.SettingChanged += (sender, args) => DoPatch();

            beamStrengthMultiplier = config.Bind(
                "Item Holder", "Beam Strength Multiplier", 1f,
                new ConfigDescription("Beam Strength Multiplier", new AcceptableValueRange<float>(min, max)));
            beamStrengthMultiplier.SettingChanged += (sender, args) => DoPatch();

            beamHeightIncrementScaleMultiplier =
                config.Bind("Item Holder", "Beam Height Increment Scale Multiplier", 1f,
                            new ConfigDescription("Beam Height Increment Scale Multiplier",
                                                  new AcceptableValueRange<float>(min, max)));
            beamHeightIncrementScaleMultiplier.SettingChanged += (sender, args) => DoPatch();

            beamPickupRangeMultiplier = config.Bind(
                "Item Holder", "Beam Pickup Range Multiplier", 1f,
                new ConfigDescription("Beam Pickup Range Multiplier", new AcceptableValueRange<float>(min, max)));
            beamPickupRangeMultiplier.SettingChanged += (sender, args) => DoPatch();

            magnetStrengthMultiplier = config.Bind(
                "Item Holder", "Magnet Strength Multiplier", 1f,
                new ConfigDescription("Magnet Strength Multiplier", new AcceptableValueRange<float>(min, max)));
            magnetStrengthMultiplier.SettingChanged += (sender, args) => DoPatch();

            magnetPickupRangeMultiplier = config.Bind(
                "Item Holder", "Magnet Pickup Range Multiplier", 1f,
                new ConfigDescription("Magnet Pickup Range Multiplier", new AcceptableValueRange<float>(min, max)));
            magnetPickupRangeMultiplier.SettingChanged += (sender, args) => DoPatch();
        }

        private static void ConfigureBeam(MultipliedObject<ModuleItemHolder> obj) {
            obj.AddField(
                new FieldConfiguration<int, float>("m_CapacityPerStack", capacityPerStackMultiplier, ShouldApply));
        }

        private static void ConfigureBeamHolder(MultipliedObject<ModuleItemHolderBeam> obj) {
            obj.AddField(new FieldConfiguration<float, float>("m_BeamStrength", beamStrengthMultiplier, ShouldApply));
            obj.AddField(new FieldConfiguration<float, float>("m_HeightIncrementScale",
                                                              beamHeightIncrementScaleMultiplier, ShouldApply));
        }

        private static void ConfigureBeamPickup(MultipliedObject<ModuleItemPickup> obj) {
            obj.AddField(new FieldConfiguration<float, float>("m_PickupRange", beamPickupRangeMultiplier, ShouldApply));
        }

        private static void ConfigureMagnetHolder(MultipliedObject<ModuleItemHolderMagnet> obj) {
            obj.AddField(new FieldConfiguration<float, float>("m_Strength", magnetStrengthMultiplier, ShouldApply));
        }

        private static void ConfigureMagnetPickup(MultipliedObject<ModuleItemPickup> obj) {
            obj.AddField(
                new FieldConfiguration<float, float>("m_PickupRange", magnetPickupRangeMultiplier, ShouldApply));
        }

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

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

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ModuleItemHolder), "OnDetaching")]
        public static void PostfixDestroy(ModuleItemHolder __instance) {
            BeamManager.OnObjectDetached(__instance);
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ModuleItemHolderBeam), "OnAttached")]
        public static void PostfixCreate(ModuleItemHolderBeam __instance) {
            var trav = Traverse.Create(__instance);
            var pickup = trav.Field("m_Pickup").GetValue<ModuleItemPickup>();

            BeamHolderManager.OnObjectAttached(__instance);
            BeamPickupManager.OnObjectAttached(pickup);
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ModuleItemHolderBeam), "OnDetaching")]
        public static void PostfixDestroy(ModuleItemHolderBeam __instance) {
            var trav = Traverse.Create(__instance);
            var pickup = trav.Field("m_Pickup").GetValue<ModuleItemPickup>();

            BeamHolderManager.OnObjectDetached(__instance);
            BeamPickupManager.OnObjectDetached(pickup);
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ModuleItemHolderMagnet), "OnAttached")]
        public static void PostfixCreate(ModuleItemHolderMagnet __instance) {
            var trav = Traverse.Create(__instance);
            var pickup = trav.Field("m_Pickup").GetValue<ModuleItemPickup>();

            MagnetHolderManager.OnObjectAttached(__instance);
            MagnetPickupManager.OnObjectAttached(pickup);
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ModuleItemHolderMagnet), "OnDetaching")]
        public static void PostfixDestroy(ModuleItemHolderMagnet __instance) {
            var trav = Traverse.Create(__instance);
            var pickup = trav.Field("m_Pickup").GetValue<ModuleItemPickup>();

            MagnetHolderManager.OnObjectDetached(__instance);
            MagnetPickupManager.OnObjectDetached(pickup);
        }

        private static void DoPatch() {
            BeamManager.ApplyAll();
            BeamHolderManager.ApplyAll();
            BeamPickupManager.ApplyAll();
            MagnetHolderManager.ApplyAll();
            MagnetPickupManager.ApplyAll();
        }

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