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

public class GameController : MonoBehaviour {

	public GameObject objectSpawner;
	public GameObject objectPlayer;
	public GameObject scoreObject;
	public GameObject timerObject;
	public float timeLimit;
	public GameObject popupTextObject;
	public AudioClip timeOverSound;

	float startTime, remainingTime;
	bool gameOver,displayResult,countingIn;
	AudioSource audio;

	int score;

	void Start () {
		audio = gameObject.GetComponent<AudioSource> ();
	}

	void Awake () {
		gameOver = false;
		displayResult = false;
		countingIn = true;
		score = 0;
		StartCoroutine(CountIn(3));
		timerObject.SetActive(false);
		scoreObject.SetActive(false);
		popupTextObject.SetActive(true);

		if (PlayerPrefs.GetInt ("enableAudio") == 0) {
			AudioListener.volume = 0.0f;
		} 
		else {
			AudioListener.volume = 1.0f;
		}
	}
	
	void Update () {
		if(!countingIn) {
			gameOver = objectPlayer.GetComponent<PlayerController>().isGameOver();
			if(!gameOver) {
				remainingTime = timeLimit - (Time.time - startTime);
				timerObject.GetComponent<Text>().text = ((int)remainingTime).ToString();
				scoreObject.GetComponent<Text>().text = score.ToString();;
				if (remainingTime <= 0) {
					objectPlayer.GetComponent<PlayerController>().setGameOver(true);
				}
			}
			else if (!displayResult) {
				if(remainingTime <= 0) {
					audio.enabled = true;
					audio.PlayOneShot (timeOverSound, 0.7f);
					popupTextObject.GetComponent<Text>().text = "TIME OVER";
					popupTextObject.SetActive(true);
					displayResult = true;
				}
				else {
					popupTextObject.GetComponent<Text>().text = "GAME OVER";
					popupTextObject.SetActive(true);
					displayResult = true;
				}
				Destroy(objectSpawner);
				PlayerPrefs.SetInt ("lastScore", score);
				StartCoroutine(FreezeScreen());
			}
		}
	}

	IEnumerator CountIn(int n) {
		if (n > 0) {
			popupTextObject.GetComponent<Text>().text = n.ToString();
			yield return new WaitForSeconds(1);
			StartCoroutine(CountIn(n-1));
		}
		else {
			popupTextObject.SetActive(false);
			timerObject.SetActive(true);
			scoreObject.SetActive(true);
			countingIn = false;
			startTime = Time.time;
			objectPlayer.GetComponent<PlayerController>().setAcceptInput(true);
		}
	}

	public void addScore(int mScore) {
		score += mScore;
	}

	IEnumerator FreezeScreen() {
		yield return new WaitForSeconds(5);
		// TODO: Fade in/out
		StartCoroutine(fadeScreen());
	}

	IEnumerator fadeScreen() {
		float fadeTime = gameObject.GetComponent<SceneFader>().BeginFade(1);
		yield return new WaitForSeconds(fadeTime);
		SceneManager.LoadScene("Result");
	}
}
