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

namespace Login.Players.Networking.Packets.User.In
{
	public static class WorldSelect
	{
		[PacketHandler("Player", USER.WORLDSELECT_REQ)]
		public static void Handle(PlayerConnection client, InPacket packet)
		{
			byte worldID = packet.ReadByte();

			WorldConnection worldConnection = WorldManager.GetWorldConnection(worldID);

			if (worldConnection != null)
			{
				//string guid = Guid.NewGuid().ToString().Replace("-", "") + Guid.NewGuid().ToString().Replace("-", "");

				byte[] guidBytes = new byte[]
				{
					0x8F, 0x08, 0x81, 0x7B, 0x59, 0x63, 0x7C, 0x7A, 0x02, 0x57, 0xD0, 0x71, 0xB3, 0x0D, 0xD1, 0x3C,
					0x17, 0x10, 0x95, 0x79, 0x98, 0x43, 0xCC, 0x00, 0x6B, 0x2B, 0x0A, 0x29, 0x23, 0x0B, 0xA8, 0x19,
					0x9B, 0x3E, 0x69, 0x51, 0x7C, 0x7A, 0x80, 0x67, 0xAA, 0x01, 0xB9, 0x01, 0x59, 0x7F, 0xC0, 0x10,
					0xA3, 0x72, 0xE7, 0x2B, 0xC5, 0x3F, 0xDA, 0x6F, 0x7F, 0x5C, 0x18, 0x20, 0x21, 0x78, 0x3F, 0x57
				};

				UInt16[] guid = new UInt16[32];

				for(Int32 i = 0; i < guidBytes.Length; i+= 2)
				{
					guid[i / 2] = (UInt16)(guidBytes[i + 1] + (guidBytes[i] << 8));
				}

				Console.WriteLine($"GUID: {BitConverter.ToString(guid.SelectMany(BitConverter.GetBytes).ToArray())}");

				PlayerManager.PlayerGUIDs.Add(new PlayerGUID(guid, client.Account.ID, DateTime.Now));

#if IS_US_BUILD
				using (Worlds.Networking.Packets.Misc.Out.WorldTransfer worldTransferRequest = new Worlds.Networking.Packets.Misc.Out.WorldTransfer(guid, client.Account.ID))
				{
					worldConnection.Send(worldTransferRequest);
				}

				using (Misc.Out.WorldTransfer worldTransfer = new Misc.Out.WorldTransfer(worldConnection, guid))
				{
					client.Send(worldTransfer);
				}
#endif

#if IS_TW_BUILD
				using (Worlds.Networking.Packets.Misc.Out.WorldTransferRequest worldTransferRequest = new Worlds.Networking.Packets.Misc.Out.WorldTransferRequest(0, worldID, client.Account.ID, client.Account.UserName, guid))
				{
					worldConnection.Send(worldTransferRequest);
				}
#endif
			}
			else
			{
				Console.WriteLine($"Failed to get World Connection for World ID: {worldID}");

				client.Disconnect();
			}
		}
	}
}