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

using FilterAPI.Networking;

using FilterBot.LoginNetworking;

using FilterBot.ZoneNetworking;

namespace FilterBot.ManagerNetworking
{
    internal class ManagerServer : Client, IDisposable
    {
        public Int32 nUserNo;
        public String sID;
        public String TransferKey;
        public UInt16 RandomID;
        public Byte[] QuickBar;

        public ZoneServer Zone;

        public FiestaCrypto Crypto;

        public ManagerServer(Int32 NUN, String SID, String TK)
            : base(IPAddress.Parse(Program.Auth.ConfigValues["ManagerBindIP"]), Convert.ToInt32(Program.Auth.ConfigValues["ManagerConnectPort"]), false)
        {
            nUserNo = NUN;
            sID = SID;
            TransferKey = TK;
        }

        public override void Connected() { }

        public void SendPacket(Packet ClientPacket)
        {
            Byte[] PacketBuffer;

            ClientPacket.ToArray(Crypto, out PacketBuffer);

            Send(PacketBuffer);
        }

        public override void Received(Byte[] Buffer)
        {
            using (var ServerPacket = new Packet(Buffer))
            {
                if (!ServerPacket.SetHeaderAndType()) { }
                else if (Program.ManagerHandlers.HasHandler(ServerPacket.Header, ServerPacket.Type))
                {
                    try
                    {
                        MethodInfo PacketMethod = Program.ManagerHandlers.GetHandler(ServerPacket.Header, ServerPacket.Type);

                        Action PacketAction = Program.ManagerHandlers.GetAction(PacketMethod, this, ServerPacket);
                        PacketAction();
                    }
                    catch (Exception Error) { Program.SendConsoleText(ConsoleColor.Red, Error.ToString()); }
                }
            }
        }

        public override void Disconnected() { }
    }
}
