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

namespace VIZ.Framework.Core
{
    /// <summary>
    /// 服务管理器
    /// </summary>
    public class ServiceManager : IServiceManager
    {
        /// <summary>
        /// 图模型服务列表
        /// </summary>
        private Dictionary<string, IService> services = new Dictionary<string, IService>();

        /// <summary>
        /// 添加图模型服务
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="service">图模型服务</param>
        public void AddService<T>(string key, T service) where T : class, IService
        {
            lock (this.services)
            {
                if (this.services.ContainsKey(key))
                    throw new Exception($"service key: {key}, is already exists");

                this.services.Add(key, service);
            }
        }

        /// <summary>
        /// 移除视图模型服务
        /// </summary>
        /// <param name="key">服务键</param>
        /// <typeparam name="T">图模型服务类型</typeparam>
        public void RemoveService<T>(string key) where T : class, IService
        {
            lock (this.services)
            {
                if (this.services.ContainsKey(key))
                {
                    this.services.Remove(key);
                }
            }
        }

        /// <summary>
        /// 获取图模型服务
        /// </summary>
        /// <typeparam name="T">图模型服务类型</typeparam>
        /// <param name="key">服务键</param>
        /// <returns>图模型服务</returns>
        public T GetService<T>(string key) where T : class, IService
        {
            if (!this.services.TryGetValue(key, out IService service))
                return default;

            return service as T;
        }

        /// <summary>
        /// 获取视图模型服务列表
        /// </summary>
        /// <typeparam name="T">图模型服务类型</typeparam>
        /// <returns>图模型服务列表</returns>
        public List<T> GetServiceList<T>() where T : class, IService
        {
            return this.services.Values.Where(p => p is T).Select(p => p as T).ToList();
        }
    }
}
