using System;
using System.Reflection;
using Harmony;
using UnityEngine;
using Unity.Entities;
using RobocraftX;
using RobocraftX.GUI.CommandLine;
using RobocraftX.Multiplayer;
using Svelto.ECS;
using Svelto.Context;

namespace ExtraCommands
{
    [HarmonyPatch]
    class CommandLineCompositionRootSaveCommandPatch
    {
        static void Postfix(UnityContext<FullGameCompositionRoot> contextHolder, EnginesRoot enginesRoot, World physicsWorld, Action reloadGame, MultiplayerInitParameters multiplayerParameters)
        {
            int engineCount = 0;
            MethodInfo commandHelp = Harmony.AccessTools.Method(Harmony.AccessTools.TypeByName("RobocraftX.GUI.CommandLine.CommandLineUtility"), "SaveCommandHelp", new Type[] { typeof(string), typeof(string) });
            foreach (Type t in typeof(CustomCommandEngine).Assembly.GetTypes())
            {
                CustomCommandAttribute[] attributes = (CustomCommandAttribute[])t.GetCustomAttributes(typeof(CustomCommandAttribute), false);
                CustomCommandEngine inst = null;
                foreach (CustomCommandAttribute attr in attributes)
                {
                    if (attr != null && t.IsSubclassOf(typeof(CustomCommandEngine)))
                    {
                        if (inst == null)
                        {
                            // create instance by getting the constructor through reflection
                            inst = (CustomCommandEngine)t.GetConstructor(new Type[] { typeof(UnityContext<FullGameCompositionRoot>), typeof(EnginesRoot), typeof(World), typeof(Action), typeof(MultiplayerInitParameters) })
                                    .Invoke(new object[] { contextHolder, enginesRoot, physicsWorld, reloadGame, multiplayerParameters });
                            // add to engineRoot
                            enginesRoot.AddEngine(inst);
                            engineCount++;
                        }
                    }
                }
            }
            // enginesRoot.AddEngine(new UnregisterCommandEngine(contextHolder, enginesRoot, physicsWorld, reloadGame, multiplayerParameters));
            Debug.Log($"Added {engineCount} custom command engines");
        }

        static MethodBase TargetMethod(HarmonyInstance instance)
        {
            Type targetType = Harmony.AccessTools.TypeByName("");
            return _ComposeMethodInfo(CommandLineCompositionRoot.Compose<UnityContext<FullGameCompositionRoot>>);
        }

        private static MethodInfo _ComposeMethodInfo(Action<UnityContext<FullGameCompositionRoot>, EnginesRoot, World, Action, MultiplayerInitParameters> a)
        {
            return a.Method;
        }
    }
}