using System;
using BepInEx.Configuration;
using HarmonyLib;

namespace TerraTech {
    [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);

        public static ConfigEntry<bool> playerOnly;
        public static ConfigEntry<float> capacityPerStackMultiplier;
        public static ConfigEntry<float> beamStrengthMultiplier;
        public static ConfigEntry<float> beamHeightIncrementScaleMultiplier;
        public static ConfigEntry<float> beamPickupRangeMultiplier;
        public static ConfigEntry<float> magnetStrengthMultiplier;
        public 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")]
        static void PostfixCreate(ModuleItemHolder __instance) {
            beamManager.OnObjectAttached(__instance);
        }

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

        [HarmonyPrefix]
        [HarmonyPatch(typeof(ModuleItemHolderBeam), "OnAttached")]
        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")]
        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")]
        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")]
        static void PostfixDestroy(ModuleItemHolderMagnet __instance) {
            var trav = Traverse.Create(__instance);
            var pickup = trav.Field("m_Pickup").GetValue<ModuleItemPickup>();

            magnetHolderManager.OnObjectDetached(__instance);
            magnetPickupManager.OnObjectDetached(pickup);
        }

        public static void DoPatch() {
            beamManager.ApplyAll();
            beamHolderManager.ApplyAll();
            beamPickupManager.ApplyAll();
            magnetHolderManager.ApplyAll();
            magnetPickupManager.ApplyAll();
        }
    }
}
