using System;
using System.Net;
using System.Net.Sockets;

namespace Zone_Fix.Networking
{
    class Listener
    {
        private Socket ListenSocket;

        public String Name;
        public Int32 ConnectPort;
        public Int32 BindPort;

        public void Start()
        {
            try
            {
                IPAddress BindIP = IPAddress.Parse(Program.BindIP);
                IPEndPoint BindEndPoint = new IPEndPoint(BindIP, BindPort);

                Program.Writer.WriteLine(WriteType.Information, false, "Starting Listener -> {0}:{1}, Name -> {2}", BindIP, BindPort, Name);

                ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                ListenSocket.Bind(BindEndPoint);
                ListenSocket.Listen(1000);

                Program.Writer.WriteLine(WriteType.Information, true, "Started Listener -> {0}:{1}, Name -> {2}", BindIP, BindPort, Name);

                ListenSocket.BeginAccept(new AsyncCallback(NewClient), ListenSocket);

                Program.Writer.WriteLine(WriteType.Information, true, "Accepting Clients -> {0}", Name);
            }
            catch (Exception Error) { Program.Writer.WriteLine(WriteType.Error, true, Error.Message); }
        }

        private void NewClient(IAsyncResult Result)
        {
            try
            {
                ListenSocket.BeginAccept(new AsyncCallback(NewClient), ListenSocket);

                Socket ClientSocket = ListenSocket.EndAccept(Result);

                HandleClient ClientHandle = new HandleClient(Name, ConnectPort, ClientSocket);
            }
            catch (Exception Error) { Program.Writer.WriteLine(WriteType.Error, true, Error.Message); }
        }
    }
}
