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


// This example roughly illustrates the proper way to add multiple players from existing
// devices. Notice how InputManager.Devices is not used and no index into it is taken.
// Rather a device references are stored in each player and we use InputManager.OnDeviceDetached
// to know when one is detached.
//
// InputManager.Devices should be considered a pool from which devices may be chosen,
// not a player list. It could contain non-responsive or unsupported controllers, or there could
// be more connected controllers than your game supports, so that isn't a good strategy.
//
// To detect a joining player, we just check the current active device (which is the last
// device to provide input) for a relevant button press, check that it isn't already assigned
// to a player, and then create a new player with it.
//
// NOTE: Due to how Unity handles joysticks, disconnecting a single device will currently cause
// all devices to detach, and the remaining ones to reattach. There is no reliable workaround
// for this issue. As a result, a disconnecting controller essentially resets this example.
// In a more real world scenario, we might keep the players around and throw up some UI to let
// users activate controllers and pick their players again before resuming.
//
// This example could easily be extended to use bindings. The process would be very similar,
// just creating a new instance of your action set subclass per player and assigning the
// device to its Device property.
//
public class PlayerManager : MonoBehaviour
{
	public GameObject playerPrefab;
    public int NumberOfPlayers { get; set; }

    public List<Player> Players
    {
        get
        {
            return m_Players;
        }

        set
        {
            m_Players = value;
        }
    }

    const int maxPlayers = 4;

    public List<Vector3> playerStartPositions = new List<Vector3>() {
        new Vector3( -1, 1, -5 ),
        new Vector3( 1, 1, -5 ),
        new Vector3( -1, -1, -5 ),
        new Vector3( 1, -1, -5 ),
    };

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

    public Player GetPlayer(int index)
    {
        if(m_Players.Count > 0)
        { 
            return m_Players[index];
        }
        return null;
    }

    public int GetPlayerListSize()
    {
        return m_Players.Count;
    }

    public Vector3 GetPlayerStartPosition(int playerIndex)
    {
        if(playerIndex > playerStartPositions.Count)
        { return Vector3.zero; }

        return playerStartPositions[playerIndex];
    }

    void Start()
	{
        //InputManager.OnDeviceDetached += OnDeviceDetached;

        foreach(PersistantPlayerInfo player in GameManager.GetPersistantGameInfo().ActivePlayers)
        {
            CreatePlayer(player);
        }

    }


	void Update()
	{

	}

    Player FindPlayerUsingDevice( InputDevice inputDevice )
	{
		var playerCount = m_Players.Count;
		for (var i = 0; i < playerCount; i++)
		{
			var player = m_Players[i];
			if (player.Device == inputDevice)
			{
				return player;
			}
		}

		return null;
	}
    
    void CreatePlayer(PersistantPlayerInfo persPlayer )
	{
        var playerPosition = playerStartPositions[NumberOfPlayers];

        var gameObject = (GameObject) Instantiate( playerPrefab, playerPosition, Quaternion.identity );
        var player = gameObject.GetComponent<Player>();
        player.Device = persPlayer.Device;
        player.DefaultColor = persPlayer.Color;
        player.m_PlayerName = persPlayer.Name;
        player.m_PlayerIndex = NumberOfPlayers;
        m_Players.Add( player );
        NumberOfPlayers++;

    }


	void RemovePlayer( Player player )
	{
        //playerStartPositions.Insert( 0, player.transform.position );
		m_Players.Remove( player );
		player.Device = null;
		Destroy( player.gameObject );
	}

    /*
    void OnGUI()
    {
        const float h = 32.0f;
        var y = 10.0f;
        int MaxPlayers = GameManager.Instance.m_PersistantGameInfo.MaxPlayers;
        int PlayerCount = GameManager.GetPersistantGameInfo().ActivePlayers.Count;

        foreach (Player player in m_Players)
        {
            GUI.Label(new Rect(10, y, 300, y + h), player.m_PlayerName + " : " + player.GetComponent<PlayerGameplay>().m_CurrentScore );
            y += h;
        }
    }
    */
}
