using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using PlayerIO.GameLibrary;
using System.Drawing;

namespace Penguin {
	[RoomType("Lobby")]
	public class Lobby : Game<Player> {
		int roomId = 0;
		int playerId = 0;
		int uniquePlayerId = 0;

		const int NumRequiredPlayers = 3; // also change in Combat.cs!!!... public override void UserJoined(Player player) {

		List<Player> actualPlayersReadyToJoinAGame = new List<Player>();

		public override void GameStarted() {
			AddTimer(delegate {
				if (actualPlayersReadyToJoinAGame.Count >= NumRequiredPlayers) {
					// surely there is a better way to do this. lol
					// oh well... game jam. no time
					List<int> ids = new List<int>();

					for (int i = 0; i < actualPlayersReadyToJoinAGame.Count; i++) {
						ids.Add(actualPlayersReadyToJoinAGame[i].id);
					}

					List<int> final = new List<int>();
					int index;
					int value;

					for (int i = 0; i < NumRequiredPlayers; i++) {
						index = Misc.RandomInt(0, ids.Count);
						value = ids[index];
						ids.RemoveAt(index);
						final.Add(value);
					}

					roomId++;
					String roomName = "room" + Misc.RandomInt(0, 99999) + "" + roomId;
					Message joinMessage = Message.Create("NetFoundOtherPlayers", roomName);
					Console.WriteLine("dispatching " + roomName);

					// I'm a noob at c#, how the f to accept index n of IEnumerable
					for (int j=0; j<final.Count; j++) {
						int finalID = final[j];
						for (int i = 0; i < actualPlayersReadyToJoinAGame.Count; i++) {
							if (actualPlayersReadyToJoinAGame[i].id == finalID) {
								actualPlayersReadyToJoinAGame[i].Send(joinMessage);
								actualPlayersReadyToJoinAGame.RemoveAt(i);
								break;
							}
						}
					}
				}
			}, 500);
		}

		public override void GameClosed() {
			Console.WriteLine("RoomId: " + RoomId);
		}

		public override void UserJoined(Player player) {
			//Message m = Message.Create("init");
			player.id = uniquePlayerId;
			uniquePlayerId++;
			//m.Add(player.Id);
			//player.Send(m);
			actualPlayersReadyToJoinAGame.Add(player);
		}

		public override void UserLeft(Player player) {
			Console.WriteLine("Player " + player.Id + " left the room");
			Broadcast("left", player.Id);
		}

		public override void GotMessage(Player player, Message message) {
			switch(message.Type) {
					/*
				case "move": {
						Letter l = letters[message.GetInteger(0)];
						l.X = message.GetInteger(1);
						l.Y = message.GetInteger(2);
						Broadcast("move", message.GetInteger(0), l.X, l.Y);
						break;
					}
				case "mouse": {
						player.X = message.GetInteger(0);
						player.Y = message.GetInteger(1);
						break;
					}
				case "activate": {
						Broadcast("activate", player.Id, message.GetInteger(0));
						break;
					}
					*/
			}
		}
	}
}
