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

namespace WMFix.Handlers
{
    class WM9110ClientHandle
    {
        Socket ClientSocket;
        Byte[] ClientBuffer;

        WM9110ServerHandle ServerHandle;

        public WM9110ClientHandle(Socket ConnectedSocket)
        {
            ClientSocket = ConnectedSocket;

            try
            {
                ServerHandle = new WM9110ServerHandle(ClientSocket);

                ClientBuffer = new Byte[Settings.Byte_Size];

                ClientSocket.BeginReceive(ClientBuffer, 0, ClientBuffer.Length, SocketFlags.None, new AsyncCallback(ClientReceive), ClientSocket);
            }
            catch(Exception Error) { Console.WriteLine("ERROR: " + Error.ToString()); }
        }

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

                Array.Resize(ref ClientBuffer, ReceiveLength);

                if (ReceiveLength == 0)
                {
                    ClientSocket.Close();
                    return;
                }

                Console.WriteLine("9110: Received From Client: " + ByteUtils.BytesToHex(ClientBuffer));

                ServerHandle.Send(ClientBuffer);

                ClientBuffer = new Byte[Settings.Byte_Size];

                ClientSocket.BeginReceive(ClientBuffer, 0, ClientBuffer.Length, SocketFlags.None, new AsyncCallback(ClientReceive), ClientSocket);
            }
            catch (Exception Error) { Console.WriteLine("ERROR: " + Error.Message); }
        }
    }
}
