using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using log4net;

namespace VIZ.Framework.Connection
{
    /// <summary>
    /// TCP连接监听
    /// </summary>
    public abstract class TcpConnectionListener : ConnListenerBase
    {
        /// <summary>
        /// 日志
        /// </summary>
        private static readonly ILog log = LogManager.GetLogger(typeof(TcpConnectionListener));

        /// <summary>
        /// TCP监听
        /// </summary>
        /// <param name="ip">IP地址</param>
        /// <param name="port">端口</param>
        public TcpConnectionListener(string ip, int port)
        {
            this.IP = ip;
            this.Port = port;

            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
            this.Listener = new TcpListener(endPoint);
        }

        /// <summary>
        /// IP地址
        /// </summary>
        public string IP { get; private set; }

        /// <summary>
        /// 端口
        /// </summary>
        public int Port { get; set; }

        /// <summary>
        /// TCP监听
        /// </summary>
        public TcpListener Listener { get; private set; }

        /// <summary>
        /// 连接的客户端终结点
        /// </summary>
        public List<TcpEndpointManager> EndpointManagers { get; private set; } = new List<TcpEndpointManager>();

        /// <summary>
        /// 开始监听
        /// </summary>
        public void Start()
        {
            this.Listener.Start();
            this.Listener.BeginAcceptTcpClient(new AsyncCallback(this.acceptTcpclient), this.Listener);
        }

        /// <summary>
        /// 销毁
        /// </summary>
        public override void Dispose()
        {
            this.EndpointManagers?.ForEach(p => p.Dispose());
            this.Listener?.Stop();
        }

        /// <summary>
        /// 创建终结点管理器
        /// </summary>
        /// <param name="tcpClient">TCP客户端</param>
        /// <returns>TCP终结点管理器</returns>
        protected abstract TcpEndpointManager CreateEndpointManager(TcpClient tcpClient);

        /// <summary>
        /// 接收到TCP连接请求
        /// </summary>
        private void acceptTcpclient(IAsyncResult result)
        {
            //获取监听事件，处理客户端请求
            TcpListener listerer = (TcpListener)result.AsyncState;
            TcpClient client = listerer.EndAcceptTcpClient(result);

            TcpEndpointManager manager = this.CreateEndpointManager(client);

            lock (this.EndpointManagers)
            {
                this.EndpointManagers.Add(manager);
            }

            manager.StartRecvMessage();

            Debug.WriteLine($"接收到TCP客户端连接，当前连接数：{this.EndpointManagers.Count}");

            this.Listener.BeginAcceptTcpClient(new AsyncCallback(this.acceptTcpclient), this.Listener);
        }
    }
}
