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

namespace Login.Worlds.Networking.Packets.Misc.In
{
	public static class WorldTransfer
	{
		[PacketHandler("World", USER.WILLLOGIN_ACK)]
		public static void Handle(WorldConnection client, InPacket packet)
		{
			UInt16 netPacketHeader = packet.ReadUInt16();
			byte worldID = packet.ReadByte();
			UInt32 userID = packet.ReadUInt32();
			string userName = packet.ReadString(18);
			UInt16[] guid = packet.ReadArray<UInt16>(32);
			byte isOK = packet.ReadByte();

			if(isOK == 1)
			{
				Console.WriteLine("IS OK, VERIFYING GUID...");
				
				Console.WriteLine($"GUID: {BitConverter.ToString(guid.SelectMany(BitConverter.GetBytes).ToArray())}");

				PlayerGUID playerGUID = PlayerManager.GrabPlayerGUID(guid);

				if(playerGUID != null)
				{
					Console.WriteLine("GUID VERIFIED, FETCHING PLAYER CONNECTION...");

					PlayerConnection playerConnection = PlayerManager.GetPlayerConnection(playerGUID.UserID);

					if(playerConnection != null)
					{
						Console.WriteLine("PLAYER CONNECTION FETCHED, SENDING WORLD TRANSFER...");

						using (Players.Networking.Packets.Misc.Out.WorldTransfer worldTransfer = new Players.Networking.Packets.Misc.Out.WorldTransfer(client, guid))
						{
							string raw = $"Type: 0x{worldTransfer.Type.ToString("X4")}, Size: 0x{worldTransfer.BinaryWriter.BaseStream.Length.ToString("X4")}, Data: {BitConverter.ToString(((MemoryStream)worldTransfer.BinaryWriter.BaseStream).ToArray())}";

							Console.WriteLine($"SENDING World Transfer packet: {raw}");

							playerConnection.Send(worldTransfer);
						}

						Console.WriteLine("WORLD TRANSFER SENT");
					}
				}
			}
			else
			{
				Console.WriteLine($"IS NOTE OK, VALUE {isOK.ToString("X")}");
			}
		}
	}
}