using System;
using System.Runtime.InteropServices;
using System.Text;

namespace GameServer
{
    class cServerPacketHandler
    {
        [DllImport("winmm.dll")]
        public static extern long timeGetTime();

        private int OPC;
        private string[] Blocks = new String[0];

        public void newPacket(int iOPC)
        {
            OPC = iOPC;
        }

        public void AddBlock(object Block)
        {
            Array.Resize(ref Blocks, Blocks.Length + 1);
            Blocks[Blocks.Length - 1] = Convert.ToString(Block);
        }

        public byte[] getPacket()
        {
            string sPacket = String.Empty;

            sPacket =
                Convert.ToString(timeGetTime()) +
                Convert.ToChar(0x20) +
                Convert.ToString(OPC) +
                Convert.ToChar(0x20);

            for (int i = 0; i < Blocks.Length; i++)
            {
                sPacket += Blocks[i].Replace(Convert.ToChar(0x20), Convert.ToChar(0x1D)) + Convert.ToChar(0x20);
            }

            //new cLog(C.MSG_DEBUG, sPacket);

            sPacket = Crypt(sPacket + Convert.ToChar(0x20) + Convert.ToChar(0x0A));

            return Encoding.Default.GetBytes(sPacket);
        }

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

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

        public void AddRoomInfo(cWRRoom Room)
        {
            AddBlock(Room.getRoomID());
            AddBlock(1);
            AddBlock(Room.getRoomStatus());
            AddBlock(Room.getIDOfPlayer(Room.getRoomMaster()));
            AddBlock(Room.getRoomName());
            AddBlock(Room.HasPassword());
            AddBlock(Room.getMaxPlayer());
            AddBlock(Room.getPlayers().Count);
            AddBlock(Room.getMapID());
            AddBlock(3);
            AddBlock(2);
            AddBlock(0);
            AddBlock(Room.getRoomMode());
            AddBlock(4);
            AddBlock(1); // 0 = unjoinable(grey room)
            AddBlock(0);
            AddBlock(0); // 1 = Room has Supermaster
            AddBlock(Room.getRoomType());
            AddBlock(Room.getLevelLimit());
            AddBlock(Room.getPremiumOnly());
            AddBlock(Room.getVoteKick());
            AddBlock(0);//autostart
            AddBlock(250); // ??
            AddBlock(Room.getPing());
            AddBlock(-1);
        }
    }
}