using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class ScoreManager : MonoBehaviour {

    [SerializeField] private float ScoreToWin;
    [SerializeField] private Canvas myCanvas;
    [SerializeField] private GameObject[] scoreMeters;
    [SerializeField] private Vector2[] scoreLocations;
    [SerializeField] private Vector2 scoreScale;

    List<Player> playerList = new List<Player>();
    List<GameObject> activeMeters = new List<GameObject>();
    Player leader;
    
    void Awake()
    {
        scoreLocations[0] = new Vector2(Screen.width / 8 * -1, Screen.height / 8 * -3.7f);
        scoreLocations[1] = new Vector2(Screen.width / 8 * -3, Screen.height / 8 * -3.7f);
        scoreLocations[2] = new Vector2(Screen.width / 8 * 1, Screen.height / 8 * -3.7f);
        scoreLocations[3] = new Vector2(Screen.width / 8 * 3, Screen.height / 8 * -3.7f);
    }

	// Use this for initialization
	void Start () {
    }

    public void Subscribe(Player p, int playerID)
    {
        playerList.Add(p);
        GameObject meter = (GameObject)Instantiate(scoreMeters[playerID], scoreLocations[playerID], Quaternion.identity);

        meter.transform.SetParent(myCanvas.transform, false);
        meter.transform.localScale = scoreScale * Screen.width / 1920;


        activeMeters.Add(meter);
        Debug.Log("METERS: " + activeMeters[activeMeters.Count - 1]);
    }

    public void GetCanvas()
    {
         myCanvas = FindObjectOfType<Canvas>();
    }
	
	// Update is called once per frame
	void Update ()
    {
        var tempLeader = playerList[0];
        for(int i = 0; i < playerList.Count;i++)
        {
            activeMeters[i].GetComponent<fillscript>().SetFill(playerList[i].GetScore() / ScoreToWin);

            if(playerList[i].GetScore() > 0 && playerList[i].GetScore() > tempLeader.GetScore())
            {
                tempLeader = playerList[i];
            }
        }

        if(tempLeader.GetScore() > 0 && tempLeader != leader)
        {
            if (leader)
            {
                leader.DeactivateCrown();
            }
            leader = tempLeader;
            leader.ActivateCrown();
        }
        if (leader)
        {
            if (leader.GetScore() >= ScoreToWin)
            {
                StartCoroutine(LoadNextLevel());
                GameObject.Find("BackgroundOverlay").GetComponent<SpriteRenderer>().color = leader.GetPlayerColor();
                for (int i = 0; i < playerList.Count; i++)
                {
                    if (playerList[i] != leader)
                    {
                        playerList[i].gameObject.SetActive(false);
                    }
                }
            }
        }
    }

    IEnumerator LoadNextLevel()
    {
        yield return new WaitForSeconds(3.5f);

        int rand = Random.Range(3, 13);
        SceneManager.LoadScene(rand);
    }
}
