using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VIZ.Framework.Connection;

namespace VIZ.Package.Connection
{
    /// <summary>
    /// Viz连接
    /// </summary>
    public class VizConnection
    {
        /// <summary>
        /// 终结点管理器集合
        /// </summary>
        private Dictionary<string, VizEndpointManager> endpointManagers = new Dictionary<string, VizEndpointManager>();

        /// <summary>
        /// 获取VIZ终结点管理器
        /// </summary>
        /// <param name="key">终结点管理器键</param>
        /// <returns>终结点管理器</returns>
        public VizEndpointManager GetEndpointManager(string key)
        {
            this.endpointManagers.TryGetValue(key, out VizEndpointManager manager);
            return manager;
        }

        /// <summary>
        /// 添加VIZ终结点管理器
        /// </summary>
        /// <param name="manager">终结点管理器</param>
        public void AddEndpointManager(VizEndpointManager manager)
        {
            manager.VizConnection = this;
            lock (this.endpointManagers)
            {
                this.endpointManagers.Add(manager.Key, manager);
            }
        }

        /// <summary>
        /// 移除UDP终结点管理器
        /// </summary>
        /// <param name="key">终结点管理器键</param>
        public void RemoveEndpointManager(string key)
        {
            lock (this.endpointManagers)
            {
                if (this.endpointManagers.ContainsKey(key))
                {
                    this.endpointManagers.Remove(key);
                }
            }
        }

        /// <summary>
        /// 销毁
        /// </summary>
        public void Dispose()
        {
            lock (this.endpointManagers)
            {
                foreach (VizEndpointManager manager in this.endpointManagers.Values)
                {
                    manager.Dispose();
                }

                this.endpointManagers.Clear();
            }
        }
    }
}