using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Svelto.ECS;

using GamecraftModdingAPI.Engines;

namespace GamecraftModdingAPI.Utility
{
    /// <summary>
    /// Keeps track of custom menu-modifying engines
    /// </summary>
    public static class MenuEngineManager
    {
        private static Dictionary<string, IApiEngine> _menuEngines = new Dictionary<string, IApiEngine>();

		private static EnginesRoot _lastEngineRoot;

        // menu engine management
        public static void AddMenuEngine(IApiEngine engine)
        {
            _menuEngines[engine.Name] = engine;
			if (_lastEngineRoot != null)
            {
				Logging.MetaDebugLog($"Registering Menu IApiEngine {engine.Name}");
                _lastEngineRoot.AddEngine(engine);
				if (typeof(IFactoryEngine).IsAssignableFrom(engine.GetType()))
                {
					((IFactoryEngine)engine).Factory = _lastEngineRoot.GenerateEntityFactory();
                }
            }
        }

        public static bool ExistsMenuEngine(string name)
        {
            return _menuEngines.ContainsKey(name);
        }

        public static bool ExistsMenuEngine(IApiEngine engine)
        {
            return ExistsMenuEngine(engine.Name);
        }

        public static IApiEngine GetMenuEngine(string name)
        {
            return _menuEngines[name];
        }

        public static string[] GetMenuEngineNames()
        {
            return _menuEngines.Keys.ToArray();
        }

        public static void RemoveMenuEngine(string name)
        {
			if (_menuEngines[name].isRemovable)
			{
				_menuEngines.Remove(name);
			}
        }

        public static void RegisterEngines(EnginesRoot enginesRoot)
        {
			_lastEngineRoot = enginesRoot;
			IEntityFactory factory = enginesRoot.GenerateEntityFactory();
            foreach (var key in _menuEngines.Keys)
            {
                Logging.MetaDebugLog($"Registering Menu IApiEngine {_menuEngines[key].Name}");
                enginesRoot.AddEngine(_menuEngines[key]);
				if (typeof(IFactoryEngine).IsAssignableFrom(_menuEngines[key].GetType()))
				{
					((IFactoryEngine)_menuEngines[key]).Factory = factory;
				}
            }
        }
    }
}