using System;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Threading;

namespace GameServer
{
    class cISC
    {
        private Socket ISCSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        public cWRClient Client;

        public void ConnectISC()
        {
            try
            {
                ISCSocket.Connect(new IPEndPoint(IPAddress.Parse(Program.ConfigClass.ISC_Ip), Program.ConfigClass.ISC_Port));
                if (ISCSocket.Connected == true)
                {
                    new cLog(C.MSG_SUCCESS, "ISC Connection Stable");
                    Thread RecvThread = new Thread(new ThreadStart(ReceiveData));
                    RecvThread.Start();
                }
            }
            catch
            {
                new cLog(C.MSG_ERROR, "Connecting to ISC Server failed");
                Console.Read();
            }
        }

        public void ReceiveData()
        {
            byte[] RecvBytes = new Byte[1024];
            byte[] RecvPacket;
            Int32 RecvBytesLen = 0;
            string strPacket;
            Client = new cWRClient(ISCSocket, 0);

            Client.SendISC(new SP_ISC_LOGIN_PACKET());

            while (true)
            {
                try
                {
                    RecvBytesLen = ISCSocket.Receive(RecvBytes);

                    if (ISCSocket.Connected == true && RecvBytesLen > 0)
                    {
                        RecvPacket = new Byte[RecvBytesLen];
                        Array.Copy(RecvBytes, RecvPacket, RecvBytesLen);
                        strPacket = Encoding.Default.GetString(RecvPacket);
                        Client.pHandler.Handle(strPacket, Client,true);
                    }
                }
                catch
                {
                }
            }
        }
    }
}