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 game-modifying engines
    /// </summary>
    public static class GameEngineManager
    {
        private static Dictionary<string, IApiEngine> _gameEngines = new Dictionary<string, IApiEngine>();

		private static EnginesRoot _lastEngineRoot;

        public static void AddGameEngine(IApiEngine engine)
        {
            _gameEngines[engine.Name] = engine;
			if (_lastEngineRoot != null)
            {
				Logging.MetaDebugLog($"Registering Game IApiEngine {engine.Name}");
                _lastEngineRoot.AddEngine(engine);
				if (typeof(IFactoryEngine).IsAssignableFrom(engine.GetType()))
                {
					((IFactoryEngine)engine).Factory = _lastEngineRoot.GenerateEntityFactory();
                }
            }
        }

        public static bool ExistsGameEngine(string name)
        {
            return _gameEngines.ContainsKey(name);
        }

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

        public static IApiEngine GetGameEngine(string name)
        {
            return _gameEngines[name];
        }

        public static string[] GetGameEngineNames()
        {
            return _gameEngines.Keys.ToArray();
        }

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

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