using System;
using System.Net;
using System.Linq;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Globalization;

namespace ServerFix
{
    class Packet
    {
        public Int32 Count { get; set; }
        public DateTime ExpireDate { get; set; }
    }

    class HandleClient
    {
        Socket ClientSocket;
        HandleListener LHandle;
        HandleServer SHandle;
        Byte[] ClientBuffer;

        public HandleClient(Socket HandleSocket, HandleListener HandleListen)
        {
            ClientSocket = HandleSocket;
            LHandle = HandleListen;

            try
            {
                SHandle = new HandleServer(ClientSocket, LHandle, this);

                ClientBuffer = new Byte[Program.Byte_Size];

                ClientSocket.BeginReceive(ClientBuffer, 0, ClientBuffer.Length, SocketFlags.None, new AsyncCallback(ClientReceive), ClientSocket);
            }
            catch (Exception Error)
            {
                Program.System.WriteError(Error.Message);

                Shutdown();
            }
        }

        private void ClientReceive(IAsyncResult Result)
        {
            try
            {
                Int32 ReceiveLength = ClientSocket.EndReceive(Result);

                Array.Resize(ref ClientBuffer, ReceiveLength);

                IPEndPoint ClientEndPoint = (IPEndPoint)ClientSocket.RemoteEndPoint;

                SHandle.Send(ClientBuffer);

                if (ReceiveLength != 0)
                {
                    ClientBuffer = new Byte[Program.Byte_Size];

                    ClientSocket.BeginReceive(ClientBuffer, 0, ClientBuffer.Length, SocketFlags.None, new AsyncCallback(ClientReceive), ClientSocket);
                }
            }
            catch (Exception Error)
            {
                Program.System.WriteError(Error.Message);

                Shutdown();
            }
        }

        private void Shutdown()
        {
            try
            {
                ClientSocket.Shutdown(SocketShutdown.Both);
                ClientSocket.Disconnect(false);
                ClientSocket.Close();

                if (ClientSocket != null) { ClientSocket.Dispose(); }
            }
            catch { }
        }
    }
}
