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

namespace WMFix.Handlers
{
    class WM9110ServerHandle
    {
        Socket ClientSocket;
        private Socket ServerSocket;
        Socket WMSocket;
        Byte[] WMBuffer;

        public Socket ServerSocket1 { get => ServerSocket; set => ServerSocket = value; }

        public WM9110ServerHandle(Socket ConnectedSocket)
        {
            ClientSocket = ConnectedSocket;

            try
            {
                IPAddress ConnectIP = IPAddress.Parse(Settings.Connect_IP);
                IPEndPoint ConnectEndPoint = new IPEndPoint(ConnectIP, Settings.Connect_Port9110);

                WMSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                WMSocket.BeginConnect(ConnectEndPoint, new AsyncCallback(WMConnect), null);
            }
            catch (Exception Error) { Console.WriteLine("1 ERROR: " + Error.Message); }
        }

        private void WMConnect(IAsyncResult Result)
        {
            try
            {
                WMSocket.EndConnect(Result);

                WMBuffer = new Byte[Settings.Byte_Size];

                WMSocket.BeginReceive(WMBuffer, 0, WMBuffer.Length, SocketFlags.None, new AsyncCallback(WMReceive), WMSocket);
            }
            catch (Exception Error) { Console.WriteLine("2 ERROR: " + Error.Message); }
        }

        private void WMReceive(IAsyncResult Result)
        {
            try
            {
                Int32 ReceiveLength = WMSocket.EndReceive(Result);

                Array.Resize(ref WMBuffer, ReceiveLength);

                Console.WriteLine("9110: Received From WM: " + ByteUtils.BytesToHex(WMBuffer));

                ClientSocket.Send(WMBuffer);

                WMBuffer = new Byte[Settings.Byte_Size];

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

        public void Send(Byte[] Buffer)
        {
            WMSocket.Send(Buffer);
        }

        public void Close()
        {
            WMSocket.Close();
        }
    }
}
