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

namespace FObjBase
{
    class TCPListen
    {
        private List<TCPConn> conns=new List<TCPConn>();
        private Socket socket;
        private IPEndPoint ep = new IPEndPoint(IPAddress.Any, 20006);
        public IPEndPoint LocalEP
        {
            get
            {
                return ep;
            }
            set
            {
                ep.Address = value.Address;
                ep.Port = value.Port;
            }
        }
        public ParsePacketHandler ParsePacket = null;
        public ConnectHandler ConnectAction;

        CancellationTokenSource cancellation;

        public TCPListen()
        {

        }

        public bool IsRunning { get; private set; }
        public void Start()
        {
            if (IsRunning)
                return;

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            
            socket.Bind(LocalEP);
            cancellation = new CancellationTokenSource();
            IsRunning = true;
            Task.Factory.StartNew(() =>
            {
                while (!cancellation.IsCancellationRequested)
                {
                    OnPoll();
                }
                IsRunning = false;
                //被关闭
            }, cancellation.Token);
        }

        public void Stop()
        {
            if (!IsRunning)
                return;
            if (cancellation != null)
                cancellation.Cancel();
            socket.Close();
        }
        //DateTime dtlast = DateTime.Now;
        //int pollcnt = 0;
        private void OnPoll()
        {
            //查新连接----------------------------------------------------------
            try
            {
                socket.Listen(5);
                //List<Socket> s = new List<Socket>();
                //s.Add(socket);
                //Socket.Select(s, null, null, -1);
                //if (s.Count > 0)
                //{
                    Socket socket2 = socket.Accept();

                    TCPConn sconn = new TCPConn(socket2)
                    {
                        ParsePacket = ParsePacket,
                        ConnectAction = ConnectAction,
                        IsConnected = true
                    };
                    sconn.Closed += (c) => { 
                        conns.Remove((TCPConn)c);
                    };
                    sconn.Start();
                    conns.Add(sconn);
                //}
            }
            catch (SocketException e)
            { 
                //socket被强制关闭了， 通知全部 conn 关闭！！！！
                
            }
        }

    }
}
