using Fiesta.Game.Networking.PacketTypes;
using Fiesta.Networking.Packets;
using Fiesta.Worlds;
using Fiesta.Worlds.Networking;
using Login.Worlds.Networking.Packets.Misc.Out;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Villain.Networking.Packets;

namespace Login.Worlds.Networking.Packets.Misc.In
{
	public static class InterconnectionRequest
	{
		[PacketHandler("World", MISC.S2SCONNECTION_REQ)]
		public static void Handle(WorldConnection client, InPacket packet)
		{
			byte echoData = packet.ReadByte();
			byte serverToID = packet.ReadByte();
			byte serverFromID = packet.ReadByte();
			byte fromWorldID = packet.ReadByte();
			byte fromZoneID = packet.ReadByte();
			UInt16 key = packet.ReadUInt16();

			if (client.World == null)
			{
				World world = WorldManager.Worlds.Find(x => x.ID == fromWorldID);

				if (world != null && world.Status == World.WorldStatus.Offline)
				{
					client.World = world;
				}
			}
			
			if(client.World != null)
			{
				using (Interconnection interconnection = new Interconnection(echoData, Interconnection.Error.None))
				{
					client.Send(interconnection);
				}
			}
			else
			{
				using (Interconnection interconnection = new Interconnection(echoData, Interconnection.Error.Unknown))
				{
					client.Send(interconnection);
				}

				client.Disconnect();
			}
		}
	}
}