using Fiesta.Login.Worlds.Networking.PacketTypes;
using Fiesta.Networking.Packets;
using Fiesta.Players.Networking;
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 Authentication
	{
		[PacketHandler("World", MISC.AUTHENTICATION)]
		public static void Handle(WorldConnection client, InPacket packet)
		{
			if (client.World == null)
			{
				byte worldID = packet.ReadByte();

				World world = WorldManager.Worlds.Find(x => x.ID == worldID);

				if (world != null && world.Status == World.WorldStatus.Offline)
				{
					client.World = world;
				}
			}

			if (client.World != null)
			{
				using (AuthenticationSuccess authenticationSuccess = new AuthenticationSuccess())
				{
					client.Send(authenticationSuccess);
				}
			}
			else
			{
				using (AuthenticationError authenticationError = new AuthenticationError(AuthenticationError.Reason.WorldIDAlreadyConnected))
				{
					client.Send(authenticationError);
				}

				client.Disconnect();
			}
		}
	}
}