using System;
using System.Net;
using System.Timers;
using System.Threading;
using System.Reflection;

using FilterAPI.Networking;

using FilterBot.ManagerNetworking;

namespace FilterBot.ZoneNetworking
{
    internal class ZoneServer : Client, IDisposable
    {
        private String ZoneID;

        public ManagerServer Manager;

        public FiestaCrypto Crypto;

        public ZoneServer(String ZID, ManagerServer MS)
            : base(IPAddress.Parse(Program.Auth.ConfigValues[String.Format("Zone{0}BindIP", ZID)]), Convert.ToInt32(Program.Auth.ConfigValues[String.Format("Zone{0}ConnectPort", ZID)]), false)
        {
            ZoneID = ZID;

            Manager = MS;
        }

        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.ZoneHandlers.HasHandler(ServerPacket.Header, ServerPacket.Type))
                {
                    try
                    {
                        MethodInfo PacketMethod = Program.ZoneHandlers.GetHandler(ServerPacket.Header, ServerPacket.Type);

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

        public override void Disconnected() { }
    }
}
