using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Rewired;
using UnityEngine;

public class GameState : MonoBehaviour
{
	private Color DS4DefaultColor = new Color(0.04313726f, 0.09411765f, 0.1098039f);

	private List<Player> _players = new List<Player>();

	private static GameState instance = null;

	void Awake()
	{
		if (instance == null)
			instance = this;
		else if (instance != this)
			Destroy(gameObject);

		Init();
	}

    public static GameState Instance
	{
        get
		{
            return instance;
        }
    }

	private void Init()
	{
		_players = new List<Player>() 
		{
			new Player(0) 
			{
				Color = new Color(0,0.4f,0.23f),
				PlayerColor = PlayerColor.Green
			},
			new Player(1) 
			{
				Color = new Color(0.83f,0,0),
				PlayerColor = PlayerColor.Red
			},
			new Player(2) 
			{
				Color = new Color(0.26f,0.03f,0.25f),
				PlayerColor = PlayerColor.Purple
			},
			new Player(3) 
			{
				Color = new Color(0,0.44f,0.58f),
				PlayerColor = PlayerColor.Blue
			}
		};

		foreach (var player in _players) 
		{
			InitPlayer(player);
		}
	}

    public List<Player> EnabledPlayers
	{
		get 
		{
			return _players.Where(x => x.Enabled).ToList();
		}
	}

	public void SetPlayerState(int playerId, bool enabled = false) 
	{
		var p = _players.FirstOrDefault(x => x.PlayerId == playerId);

		if (p != null) 
		{
			p.Enabled = enabled;
		}
	}

	public void Reset() 
	{
		Init();
	}

	public void InitPlayer(int playerId) 
	{
		var p = _players.FirstOrDefault(x => x.PlayerId == playerId);

		if (p != null)
		{
			InitPlayer(p);
		}
	}

	public void InitPlayer(Player player) 
	{
		var p = ReInput.players.GetPlayer(player.PlayerId);

		foreach (var joystick in p.controllers.Joysticks) 
		{
			// Rumble if supported
			if (joystick.supportsVibration) 
			{
				joystick.SetVibration(0.5f, 0.5f, 0.5f, 0.5f);
			}

			// Set controller light color if supported
			var ds4 = joystick.GetExtension<Rewired.ControllerExtensions.DualShock4Extension>();
			if (ds4 != null) 
			{
				//ds4.SetLightColor(DS4DefaultColor.r, DS4DefaultColor.g, DS4DefaultColor.b, 0.5f);

				switch (player.PlayerColor) 
				{
					case PlayerColor.Green: 
					{
						ds4.SetLightColor(Color.green);
						break;
					}
					case PlayerColor.Red: 
					{
						ds4.SetLightColor(Color.red);
						break;
					}
					case PlayerColor.Purple: 
					{
						ds4.SetLightColor(Color.magenta);
						break;
					}
					case PlayerColor.Blue: 
					{
						ds4.SetLightColor(Color.blue);
						break;
					}
				}
			}
		}
	}
}
