using System.Collections.Generic;

namespace WS
{
    ///<summary>Controller 管理</summary>
    public class ControllerManager : WSComponent
    {
        ///<summary>所有控制器</summary>
        private List<BaseController> _AllController = new List<BaseController>();

        /// <summary>注册/创建控制器</summary>
        /// <param name="isenterlibrary">是否存入集合(存入后不能重复创建)</param>
        public T CreateController<T>(bool isenterlibrary = true)
            where T : BaseController
        {
            BaseController controller = null;
            if (isenterlibrary)
            {
                controller = GetController<T>();
                if (controller == null)
                {
                    controller = ComponentFactory.Create<T>();
                    _AllController.Add(controller);
                }
                else
                {
                    Log.LogError($"已经注册{controller.GetType().Name}!");
                }
            }
            else
            {
                controller = ComponentFactory.Create<T>();
            }
            return controller as T;
        }

        ///<summary>删除控制器</summary>
        public void RemoveController<T>()
            where T : BaseController
        {
            BaseController controller = GetController<T>();
            if (controller != null)
            {
                controller.Dispose();
                _AllController.Remove(controller);
            }
            else
            {
                Log.LogError($"注册列表中没有找到该类型Controller {typeof(T).Name}!");
            }
        }

        ///<summary>删除控制器</summary>
        public void RemoveController(BaseController controller)
        {
            if (controller == null)
                return;
            controller.Dispose();
            if (_AllController.Exists(p => p == controller))
            {
                _AllController.Remove(controller);
            }
        }

        ///<summary>删除所有控制器</summary>
        public void RemoveAllController()
        {
            for (int i = 0; i < _AllController.Count; i++)
            {
                _AllController[i].Dispose();
            }
            _AllController.Clear();
        }

        /// <summary>获取控制器</summary>
        public T GetController<T>()
            where T : BaseController
        {
            for (int i = 0; i < _AllController.Count; i++)
            {
                if (_AllController[i] is T)
                {
                    return _AllController[i] as T;
                }
            }
            return null;
        }

        public override void Dispose()
        {
            base.Dispose();
            RemoveAllController();
        }
    }
}
