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

public class GameManager : MonoBehaviour {

	public ComparePalace ComparePalace;

	public ProgressBar ProgressBar;

	public GridToCopy GridToCopy;

	public Animator WashAnimator;

	public Grid Grid;

	public Text LevelText;

	private int level;

	private bool isWashing;

	public static bool GameOver;

	public GameObject GameOverGUI;

	public Text CastlesBuilt;

	public AudioSource WaveAudio;

	public AudioSource YayAudio;

	public AudioSource FailedAudio;

	// Use this for initialization
	void Start () {
		isWashing = false;
		level = 1;
		GameOver = false;
	}
	
	// Update is called once per frame
	void Update () {
		if(GameOver) return;

		if(ComparePalace.IsCorrect() && !isWashing)
		{
			isWashing = true;
			ProgressBar.StopProgress();
			StartCoroutine(WashGame());
		}
		if(ProgressBar.ActiveTime <= 0)
		{
			GameOver = true;
			WashAnimator.SetTrigger("GameOverWash");
			WaveAudio.Play();
			LevelText.enabled = false;	
			CastlesBuilt.text = "You Built " + (level - 1) + " Castles!"; 
			ProgressBar.gameObject.SetActive(false);
			StartCoroutine(ShowGameOverGUI());
			FailedAudio.Play();
		}
	}

    private IEnumerator ShowGameOverGUI()
    {
		yield return new WaitForSeconds(1.5f);
        GameOverGUI.SetActive(true);
    }

    private IEnumerator WashGame()
    {
		LevelText.enabled = false;
		ProgressBar.gameObject.SetActive(false);
		WashAnimator.SetTrigger("Wash");
		WaveAudio.Play();
		YayAudio.Play();
		yield return new WaitForSeconds(1f);
		Grid.Clean();
		level++;
		LevelText.text = "Level " + level;
		if(level % 3 == 2)
			GridToCopy.HideSome();
		else if(level % 3 == 0)
			GridToCopy.HideAll();
		else
			GridToCopy.RandomizeCastle();
		yield return new WaitForSeconds(1.5f);
		ProgressBar.gameObject.SetActive(true);
        ProgressBar.ResetProgress();
		ProgressBar.StartProgress();
		isWashing = false;
		LevelText.enabled = true;
    }
}
