using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class TimeKeeper : MonoBehaviour {

    public float TotalTime = 60.0f;
    private float EndTime = 0.0f;

    public Text textTimeRemaining = null;

    public Slider[] shapeSliders = null;

    public float BonusTime = 15.0f;

    public void ShapeDestroyedHandler(int shapeID)
    {
        int sliderIndex = shapeID - 1;
        shapeSliders[sliderIndex].value += 1;
    }

    public bool TimeOver
    {
        get
        {
            return Time.time > EndTime;
        }
    }

	// Use this for initialization
	void Start () {
        EndTime = Time.time + TotalTime;
	}
	
	// Update is called once per frame
	void Update () {

        if (Debug.isDebugBuild)
        {
            // Cheat off 5 seconds
            if (Input.GetKeyDown(KeyCode.T))
            {
                EndTime -= 5.0f;
            }
        }

        float timeRemaining = EndTime - Time.time;

        // Update the text display
        float timeToDisplay = Mathf.Max(0.0f, timeRemaining);
        textTimeRemaining.text = timeToDisplay.ToString("0.0");

        if (timeRemaining <= -1.0f 
            && GameManager.Instance.gameObject.GetComponent<ShapeManager>().NoPiecesAreFalling() 
            && GameManager.Instance.ScoreAccumulator.DisplayedTotalScore == GameManager.Instance.ScoreAccumulator.TotalScore)
        {
            GameSettings.LastScore = GameManager.Instance.ScoreAccumulator.TotalScore;
            SceneManager.LoadScene("ScoreScreen");
        }
        else
        {
            bool allMaxed = true;
            foreach(Slider s in shapeSliders)
            {
                if (s.value < s.maxValue)
                    allMaxed = false;
            }

            if (allMaxed)
            {
                // BONUS TIME
                foreach(Slider s in shapeSliders)
                {
                    s.value = 0;
                }
                EndTime += BonusTime;

                // Play sound effect here
                GetComponent<SoundRandomizer>().Play();

                transform.Find("ExtraTime").gameObject.GetComponent<TimeExtender>().ExtendTime(BonusTime);
            }
        }
	}
}
