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

namespace VIZ.Framework.Connection
{
    /// <summary>
    /// TCP链接
    /// </summary>
    public class TcpConnection : IDisposable
    {
        /// <summary>
        /// 终结点管理器集合
        /// </summary>
        private Dictionary<string, TcpEndpointManager> endpointManagers = new Dictionary<string, TcpEndpointManager>();

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

        /// <summary>
        /// 添加TCP终结点管理器
        /// </summary>
        /// <param name="manager">终结点管理器</param>
        public void AddEndpointManager(TcpEndpointManager manager)
        {
            manager.TcpConnection = 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 (TcpEndpointManager manager in this.endpointManagers.Values)
                {
                    manager.Dispose();
                }

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