﻿using UnityEngine;
using System;
using System.Collections.Generic;
using InControl;

public class PlayerSelection : MonoBehaviour
{
	//Set through Unity
	public PlayerSelect[] PlayerSelects;
	//

	PlayerActions playerActions;
	
	void Awake()
	{
		PlayerManager.Instance.Reset();
	}
	
	void OnEnable()
	{
		this.playerActions = PlayerActions.CreateWithJoystickBindings();
		
//		InputManager.OnDeviceDetached += this.OnDeviceDetached;
	}
	
	void Update () 
	{
		if (this.playerActions.YesOrOk.WasPressed)
		{
			var inputDevice = InputManager.ActiveDevice;
			
			if (PlayerManager.Instance.IsInputDeviceFree(inputDevice))
			{
				var newPlayerActions = PlayerActions.CreateWithJoystickBindings();
				newPlayerActions.Device = inputDevice;
				
				foreach(var playerSelect in this.PlayerSelects)
				{
					if (playerSelect.PlayerActions == null)
					{
						playerSelect.AssignPlayerActions(newPlayerActions);
						break;
					}
				}
			}
		}
		
		int ready = 0;
		foreach(var playerSelect in this.PlayerSelects)
		{
			if (playerSelect.IsReady)
			{
				ready++;
			}
		}
		
		if (ready >= 2)
		{
			Application.LoadLevel("Level1");
		}
	}

//	void OnDeviceDetached (InputDevice device)
//	{
//		throw new NotImplementedException ();
//	}
}
