using System;
using BepInEx.Configuration;
using HarmonyLib;

namespace BanquetForCyka {
    [HarmonyPatch]
    public class ModuleFuelTankManager {
        private static readonly MultipliedObjectManager<ModuleFuelTank> Manager =
            new MultipliedObjectManager<ModuleFuelTank>(ConfigureFuelTank);

        private static ConfigEntry<bool> playerOnly;
        private static ConfigEntry<float> fuelCapacityMultiplier;
        private static ConfigEntry<float> fuelRefillMultiplier;

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

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

            fuelCapacityMultiplier = config.Bind(
                "FuelTank", "Fuel Capacity Multiplier", 1f,
                new ConfigDescription("Fuel Capacity Multiplier", new AcceptableValueRange<float>(min, max)));
            fuelCapacityMultiplier.SettingChanged += (sender, args) => DoPatch();

            fuelRefillMultiplier =
                config.Bind("FuelTank", "Fuel Refill Multiplier", 1f,
                            new ConfigDescription("Fuel Refill Multiplier", new AcceptableValueRange<float>(min, max)));
            fuelRefillMultiplier.SettingChanged += (sender, args) => DoPatch();
        }

        private static void ConfigureFuelTank(MultipliedObject<ModuleFuelTank> obj) {
            obj.AddField(new FieldConfiguration<float, float>("m_Capacity", fuelCapacityMultiplier, ShouldApply));
            obj.AddField(new FieldConfiguration<float, float>("m_RefillRate", fuelRefillMultiplier, ShouldApply));
        }

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

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

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