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

using FilterAPI.Networking;

namespace FilterRest.LocalNetworking
{
    internal class LocalClient : Client, IDisposable
    {
        public LocalClient()
            : base(IPAddress.Parse(Program.Auth.ConfigValues["CentralBindIP"]), Convert.ToInt32(Program.Auth.ConfigValues["CentralBindPort"])) { }

        public override void Connected() { }

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

            ServerPacket.ToArray(out PacketBuffer);

            Send(PacketBuffer);
        }

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

                        Action PacketAction = Program.LocalHandlers.GetAction(PacketMethod, this, ClientPacket);
                        PacketAction();
                    }
                    catch { }
                }
            }
        }
        public override void Disconnected() { Program.LocalClient = new LocalClient(); }
    }
}
