using System;
using System.Collections.Generic;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;

namespace Ereshor {
    [HarmonyPatch]
    public class TankManager {
        public static ConfigEntry<bool> recheck;
        public static Dictionary<Type, Func<Module, bool>> moduleManagerMapper =
            new Dictionary<Type, Func<Module, bool>>();

        public static void Setup(ConfigFile config) {
            recheck = config.Bind("Tank", "Recheck", false, new ConfigDescription("Recheck"));
            moduleManagerMapper.Add(typeof(ModuleBooster), ModuleBoosterManager.Register);
            moduleManagerMapper.Add(typeof(ModuleEnergy), ModuleEnergyManager.Register);
            moduleManagerMapper.Add(typeof(ModuleEnergyStore), ModuleEnergyStoreManager.Register);
            moduleManagerMapper.Add(typeof(ModuleFuelTank), ModuleFuelTankManager.Register);
            moduleManagerMapper.Add(typeof(ModuleGyro), ModuleGyroManager.Register);
            moduleManagerMapper.Add(typeof(ModuleHeart), ModuleHeartManager.Register);
            moduleManagerMapper.Add(typeof(ModuleItemHolder), ModuleItemHolderManager.Register);
            moduleManagerMapper.Add(typeof(ModuleItemProducer), ModuleItemProducerManager.Register);
            moduleManagerMapper.Add(typeof(ModuleRemoteCharger), ModuleRemoteChargerManager.Register);
            moduleManagerMapper.Add(typeof(ModuleShieldGenerator), ModuleShieldGeneratorManager.Register);
            moduleManagerMapper.Add(typeof(ModuleWeaponGun), ModuleWeaponGunManager.Register);
            moduleManagerMapper.Add(typeof(ModuleWeapon), ModuleWeaponManager.Register);
            moduleManagerMapper.Add(typeof(ModuleWheels), ModuleWheelsManager.Register);
            moduleManagerMapper.Add(typeof(ModuleWing), ModuleWingManager.Register);
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(Tank), "NotifyAnchor")]
        public static void PostfixCreate(Tank __instance, ModuleAnchor anchor, bool anchored) {
            if (Main.debug.Value)
                Console.WriteLine("TankManager.NotifyAnchor: {0}", __instance);
            if (!__instance.ControllableByLocalPlayer)
                return;
            if (!recheck.Value)
                return;

            foreach (Transform child in __instance.transform) {
                GameObject childObj = child.gameObject;
                Component[] components = childObj.GetComponents<Component>();
                foreach (Component component in components) {
                    Func<Module, bool> manager;
                    if (moduleManagerMapper.TryGetValue(component.GetType(), out manager))
                        manager(component as Module);
                }
            }
        }
    }
}
