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

using Console = Villain.Output.Console;

namespace World.Login.Networking.Packets
{
	class Misc
	{
		public enum In : UInt16
		{
			AuthenticationFail = 0x0102,
			AuthenticationSuccess = 0x0103
		}

		public enum Out : UInt16
		{
			Authentication = 0x0101,
			StatusUpdate = 0x0104
		}

		[PacketHandler("Login", In.AuthenticationFail)]
		public static void AuthenticationFail(Client client, InPacket packet)
		{
			try
			{
				byte reasonCode = packet.Readbyte();

				switch (reasonCode)
				{
					case 0x01:
						Console.WriteLine("The Login server already has a connection to this world ID", ConsoleColor.Red);
						break;
				}
			}
			catch
			{
				Console.WriteLine("The Login server refused the connection for an unknown reason", ConsoleColor.Red);
			}
			
			Program.Shutdown();
		}

		[PacketHandler("Login", In.AuthenticationSuccess)]
		public static void AuthenticationSuccess(Client client, InPacket packet)
		{
			using (StatusUpdate statusUpdate = new StatusUpdate())
			{
				client.Send(statusUpdate);
			}
		}

		public class Authentication : OutPacket
		{
			public Authentication(byte worldID) : base(Out.Authentication)
			{
				Writebyte(worldID);
			}
		}

		public class StatusUpdate : OutPacket
		{
			public StatusUpdate() : this(Program.WorldStatus)
			{

			}

			public StatusUpdate(Fiesta.Worlds.World.WorldStatus status) : base(Out.StatusUpdate)
			{
				Writebyte((byte)status);
			}
		}
	}
}