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

[System.Serializable]
public class PersistantGameInfo
{
    public List<PersistantPlayerInfo> ActivePlayers;
    public List<PersistantPlayerInfo> GetActivePlayers()
    {
        return ActivePlayers;
    }
    public int NumberOfPlayers { get { return ActivePlayers.Count;  } }
    public int MaxPlayers = 4;

    private List<Color> AvailableColors = new List<Color>() {
         Color.blue,
         Color.red,
         Color.green,
         Color.yellow,
         Color.white,
         Color.magenta
    };

    private List<string> AvailableNames = new List<string>() {
         "Player1",
         "Player2",
         "Player3",
         "Player4",
         "Player5",
         "Player6"
    };

    public PersistantGameInfo()
    {
        ActivePlayers = new List<PersistantPlayerInfo>();
    }

    public void Reset()
    {
        ClearPlayers();
    }

    public PersistantPlayerInfo GetPlayerUsingDevice(InputDevice _inputDevice)
    {
        for (int i = 0; i < ActivePlayers.Count; ++i)
        {
            PersistantPlayerInfo player = ActivePlayers[i];
            if (player.Device == _inputDevice)
            {
                return player;
            }
        }

        return null;
    }

    public PersistantPlayerInfo GetPlayerUsingColor(Color _color)
    {
        for (int i = 0; i < ActivePlayers.Count; ++i)
        {
            PersistantPlayerInfo player = ActivePlayers[i];
            if (player.Color == _color)
            {
                return player;
            }
        }

        return null;
    }

    public void AddPlayer(InputDevice _device)
    {
        Debug.Log("Adding " + AvailableNames[NumberOfPlayers] + " with color " + AvailableColors[NumberOfPlayers]);

        ActivePlayers.Add(new PersistantPlayerInfo(_device, AvailableColors[NumberOfPlayers], AvailableNames[NumberOfPlayers]));
    }

    public void ClearPlayers()
    {
        ActivePlayers.Clear();
    }

    public bool IsSessionFull()
    {
        return (ActivePlayers.Count == MaxPlayers);
    }

    public string GetWinnerString()
    {
        int highscore = -1;
        string value = "Tie Game";

        for (int i = 0; i < ActivePlayers.Count; ++i)
        {
            PersistantPlayerInfo player = ActivePlayers[i];
            if (player.Score > highscore)
            {
                highscore = player.Score;
                value = player.Name + " Wins with " + highscore + "points";
            }
        }

        return value;
    }
}
