using BepInEx.Configuration;
using HarmonyLib;

namespace TerraTech {
    [HarmonyPatch]
    public class TankBeamManager {
        private static readonly MultipliedObjectManager<TankBeam> Manager =
            new MultipliedObjectManager<TankBeam>(ConfigureBeam);

        public static ConfigEntry<float> hoverClearanceMultiplier;
        public static ConfigEntry<float> nudgeSpeedForwardMultiplier;
        public static ConfigEntry<float> nudgeSpeedRotateMultiplier;

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

            hoverClearanceMultiplier = config.Bind(
                "TankBeam", "Hover Clearance Multiplier", 1f,
                new ConfigDescription("Hover Clearance Multiplier", new AcceptableValueRange<float>(min, max)));
            hoverClearanceMultiplier.SettingChanged += (sender, args) => DoPatch();

            nudgeSpeedForwardMultiplier = config.Bind(
                "TankBeam", "Nudge Speed Forward Multiplier", 1f,
                new ConfigDescription("Nudge Speed Forward Multiplier", new AcceptableValueRange<float>(min, max)));
            nudgeSpeedForwardMultiplier.SettingChanged += (sender, args) => DoPatch();

            nudgeSpeedRotateMultiplier = config.Bind(
                "TankBeam", "Nudge Speed Rotate Multiplier", 1f,
                new ConfigDescription("Nudge Speed Rotate Multiplier", new AcceptableValueRange<float>(min, max)));
            nudgeSpeedRotateMultiplier.SettingChanged += (sender, args) => DoPatch();
        }

        private static void ConfigureBeam(MultipliedObject<TankBeam> obj) {
            obj.AddField(new FieldConfiguration<float, float>("hoverClearance", hoverClearanceMultiplier));
            obj.AddField(new FieldConfiguration<float, float>("nudgeSpeedForward", nudgeSpeedForwardMultiplier));
            obj.AddField(new FieldConfiguration<float, float>("nudgeSpeedRotate", nudgeSpeedRotateMultiplier));
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(TankBeam), "EnableBeam")]
        public static void PostfixCreate(TankBeam __instance, ref bool enable) {
            if (enable)
                Manager.OnObjectAttached(__instance);
            else
                Manager.OnObjectDetached(__instance);
        }

        public static void DoPatch() {
            Manager.ApplyAll();
        }
    }
}
