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

public class GameController : MonoBehaviour {
    public Spectator[] spectators;
    public int soundPlaying;
    public float performance;
    public float totalPerformanceNeeded;
    public float points=10;
    public float pitchPenalty=0.1f;
    public AudioController audioController;
    public bool gameOver, win, lost;
    public RectTransform victory, lose;
    public Outline flash;
    public float gameOverTextSpeed, gameOverTextFrame;
    public float finalY;
	// Use this for initialization
	void Start () {
        soundPlaying = -1;
        performance = totalPerformanceNeeded / 2;
	}
	
	// Update is called once per frame
	void Update () {
        if (soundPlaying != -1)
        {
            if (!gameOver)
            {
                foreach (Spectator s in spectators)
                {
                    performance += s.deGustibus[soundPlaying] * points * Time.deltaTime - pitchPenalty * Mathf.Log(Mathf.Abs(1 + audioController.pitchError), 1 + audioController.maxPitch) * Time.deltaTime;
                }
                if (performance >= totalPerformanceNeeded)
                {
                    gameOver = true;
                    win = true;
                    AllJump();
                }
                if (performance <= 0)
                {
                    gameOver = true;
                    lost = true;
                    Loser();
                }
            }
        }
	}
    void AllJump() {
        foreach(Spectator s in spectators)
        {
            s.deGustibus[soundPlaying] = 3;
        }
        StartCoroutine(MoveTextUp(victory));
        StartCoroutine(FlashText());
    }
    void Loser()
    {
        foreach (Spectator s in spectators)
        {
            s.deGustibus[soundPlaying] = -3;
        }
        StartCoroutine(MoveTextUp(lose));
    }

    IEnumerator MoveTextUp(RectTransform textToMove)
    {
        audioController.gameOver();
        do
        {
            float newY = Mathf.MoveTowards(textToMove.anchoredPosition.y, finalY, gameOverTextSpeed);
            textToMove.anchoredPosition = new Vector2(textToMove.anchoredPosition.x, newY);
            yield return new WaitForSeconds(gameOverTextFrame);
        }
        while (textToMove.anchoredPosition.y < finalY);
        // Restart the game
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
    IEnumerator FlashText()
    {
        do
        {
            if (flash.effectColor.a == 1) flash.effectColor = new Color(flash.effectColor.r, flash.effectColor.g, flash.effectColor.b, 0);
            else flash.effectColor = new Color(flash.effectColor.r, flash.effectColor.g, flash.effectColor.b, 1);
            yield return new WaitForSeconds(20 * gameOverTextFrame);
        }
        while (true);
    }
}
