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

using Svelto.ECS;

using GamecraftModdingAPI.Utility;

namespace GamecraftModdingAPI.Commands
{
    /// <summary>
    /// Keeps track of custom commands
    /// This is used to add, remove and get command engines
    /// </summary>
    public static class CommandManager
    {
        private static Dictionary<string, ICustomCommandEngine> _customCommands = new Dictionary<string, ICustomCommandEngine>();

		private static EnginesRoot _lastEngineRoot;

        public static void AddCommand(ICustomCommandEngine engine)
        {
			if (ExistsCommand(engine))
			{
				throw new CommandAlreadyExistsException($"Command {engine.Name} already exists");
			}
            _customCommands[engine.Name] = engine;
			if (_lastEngineRoot != null)
            {
                Logging.MetaDebugLog($"Registering ICustomCommandEngine {engine.Name}");
                _lastEngineRoot.AddEngine(engine);
            }
        }

        public static bool ExistsCommand(string name)
        {
            return _customCommands.ContainsKey(name);
        }

        public static bool ExistsCommand(ICustomCommandEngine engine)
        {
            return ExistsCommand(engine.Name);
        }

        public static ICustomCommandEngine GetCommand(string name)
        {
            return _customCommands[name];
        }

        public static string[] GetCommandNames()
        {
            return _customCommands.Keys.ToArray();
        }

        public static void RemoveCommand(string name)
        {
            _customCommands.Remove(name);
        }

        public static void RegisterEngines(EnginesRoot enginesRoot)
        {
			_lastEngineRoot = enginesRoot;
            foreach (var key in _customCommands.Keys)
            {
                Logging.MetaDebugLog($"Registering ICustomCommandEngine {_customCommands[key].Name}");
                enginesRoot.AddEngine(_customCommands[key]);
            }
        }
    }
}