using System;
using System.Text;

namespace GameServer
{
    class cClientPacketHandler
    {
        public string[] Blocks;
        private int OPC = 0;
        private long TimeStamp = 0;
        private int c = 0;

        public virtual void HandlePacket(cClientPacketHandler Packet, cWRClient Client)
        {
        }

        public virtual void Handle(string sPacket, cWRClient Client,bool isISC)
        {
            string tPacket;
            if (isISC)
            {
                tPacket = deCrypt(sPacket);
            }
            else
            {
                tPacket = deCrypt2(sPacket);
            }

         
            Blocks = tPacket.Split(new char[] { ' ' });
            TimeStamp = long.Parse(Blocks[0]);
            OPC = int.Parse(Blocks[1]);
            if (OPC != 25088 && OPC != 91337 && OPC != 28673 && OPC != 44441 && Client.isLoggedin == false && isISC == false)
            {
                try
                {
                    Client.Disconnect();
                }
                catch (Exception ex)
                {

                }
            }
            if (OPC != 25600)
            {
                new cLog(C.MSG_DEBUG, tPacket);
            }
            c = 0;
            Array.Copy(Blocks, 2, Blocks, 0, Blocks.Length - 2);

            if (Program.ServerClass.hTable.ContainsKey(OPC))
            {
                cClientPacketHandler Handler = (cClientPacketHandler)Program.ServerClass.hTable[OPC];
                Handler.HandlePacket(this, Client);
                
            }
            else
            {
                new cLog(C.MSG_ERROR, "No Handler for OPC: " + OPC);
                new cLog(C.MSG_DEBUG, "New Unknown Packet: " + tPacket);
            }
        }

        public string getPacket()
        {
            for (int i = 1; i < Blocks.Length; i++)
            {
                return Blocks[i];
            }
            return null;
        }
        public string getBlock()
        {
            string Block = Blocks[c];
            c++;
            return Block;
        }

        public string[] getAllBlocks()
        {
            return Blocks;
        }

        public string getBlockByIndex(int Index)
        {
            return Blocks[Index];
        }

        public string deCrypt(string sPacket)
        {
            byte[] tTemp = Encoding.Default.GetBytes(sPacket);

            for (int i = 0; i < tTemp.Length; i++)
            {
                tTemp[i] = Convert.ToByte(tTemp[i] ^ 0xC3);
            }
            return Encoding.Default.GetString(tTemp);
        }
        public string deCrypt2(string sPacket)
        {
            byte[] tTemp = Encoding.Default.GetBytes(sPacket);

            for (int i = 0; i < tTemp.Length; i++)
            {
                tTemp[i] = Convert.ToByte(tTemp[i] ^ 0x45);
            }
            return Encoding.Default.GetString(tTemp);
        }
    }
}
