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

public class LevelManager : MonoBehaviour {

	public int levelDuration = 120;
    public float scoreWaitDuration = 0.2f;
	public Text timerLabel;
	public Text charThinkingCounterLabel;
	public Text percentDominatedLabel;
	public Text scoreLabel;
    public Text resultMindDominations;
    public Text resultTotalDominations;
    public Text resultComboDominations;
    public Text resultFinalScore;
    public GameObject scoreManager;
    public AudioClip[] audioClips;

    private static int charsThinking = 0;

	private GameObject[] tvs;
	private int remainingTime;
	private GameObject tvGroup;
	private int percentDominated;

	private bool levelRunning = true;
	public bool LevelRunning {
		get {
			return levelRunning;
		}
	}

    private GameObject panelGameOver;

	// These two variables are used to replace the end condition of 100% dominated with combos (multipliers)
	private int countCharsDominatedPreviousFrame = 0;
	private int comboCounter = 0;

    private AudioSource audioSource;

	void Awake() {
		remainingTime = levelDuration;
		tvs = GameObject.FindGameObjectsWithTag("TV");
		tvGroup = GameObject.Find("TVGroup");
		percentDominated = 0;
        panelGameOver = GameObject.Find("PanelGameOver");
        panelGameOver.SetActive(false);
        audioSource = gameObject.GetComponent<AudioSource>();
}

	// Use this for initialization
	void Start () {
        audioSource.clip = audioClips[0];
        audioSource.Play();
		InvokeRepeating("DecrementTime", 0.00001f, 1f);
	}

	void DecrementTime() {
		if(timerLabel != null) {
			timerLabel.text = string.Format("{0:D2}:{1:D2}", remainingTime / 60, remainingTime % 60);
		}
		--remainingTime;
	}
	
	// Update is called once per frame
	void Update () {
		if(levelRunning) {
			UpdatePercentTotalDomination();
            CheckForLevelEndCondition();
        }
	}

	void UpdatePercentTotalDomination() {
		int count = 0;

		for(int i = 0; i < tvs.Length; i++) {
			StateType state = tvs[i].GetComponent<StateChange>().State;
			if(state == StateType.Thinking) count++;
		}

		// Calculate the amount of combos based on the number of "dominated" chars from the previous and current frame:
		// If in the previous frame the # of dominated chars was smaller than the total of chars...
		// but on the current frame the number (count) is equal to the # of total chars...
		// we are transitioning from a % dominated smaller than 100% to 100%...
		// then we increment the combo counter;
		if(countCharsDominatedPreviousFrame < tvs.Length && count == tvs.Length) {
			comboCounter++;
		}
		countCharsDominatedPreviousFrame = count;

		percentDominated = (int)((float)count / (float)tvs.Length * 100.0);

		if(percentDominatedLabel != null) {
			percentDominatedLabel.text = string.Format("{0} %", percentDominated);
		}
	}

	void CheckForLevelEndCondition() {
		if(remainingTime < 0 /*|| percentDominated >= 100*/) {
			levelRunning = false;
			CancelInvoke("DecrementTime");
			DisableTVs();
            StartCoroutine(CalculateScore());
		}
	}

	public void CharIsThinking() {
		++charsThinking;
		charThinkingCounterLabel.text = string.Format("x {0}", charsThinking);
	}

	void DisableTVs() {
		if(tvGroup != null) {
			tvGroup.SetActive(false);
		}
	}

    IEnumerator CalculateScore() {
        int finalScore = 0;
        int mindDominationsScore = 0;
        int totalDominationsScore = 0;
        int cont = 0;

        panelGameOver.SetActive(true);
        
        mindDominationsScore =  charsThinking;
        
        totalDominationsScore = percentDominated;

        finalScore = (mindDominationsScore * 100) + (totalDominationsScore * 150) + (comboCounter * 5000);

        while (cont <= finalScore) {
            if (charsThinking > 0) charsThinking -= 1;
            if (percentDominated > 0) percentDominated -= 1;
            if (comboCounter > 0) comboCounter -= 1;
            yield return StartCoroutine(UpdateLabels(cont));
            cont+=200;
        }

        resultMindDominations.text = "0";
        resultTotalDominations.text = "0";
        resultComboDominations.text = "0";

        scoreManager.GetComponent<ScoreManager>().AddScore(finalScore);
    }

    IEnumerator UpdateLabels(int finalScore) {
        resultMindDominations.text = (charsThinking > 0) ? charsThinking.ToString() : "0";
        resultTotalDominations.text = (percentDominated > 0) ? percentDominated.ToString() : "0";
        resultComboDominations.text = (comboCounter > 0) ? comboCounter.ToString() : "0";
        resultFinalScore.text = finalScore.ToString();
        yield return new WaitForSeconds(scoreWaitDuration);
    }

    public void GoToHighScoreScreen() {
        SceneManager.LoadScene("HighScores");
    }
}
