using UnityEngine;
using System.Collections;

public class ChapterTimer : MonoBehaviour {

    public TextMesh textMesh;

    public float clockVolume;
    public AudioClip clock1;
    public AudioClip clock2;

    private IEnumerator coroutine;
    private GameObject soundManager;

	// Use this for initialization
	void Start () {
        soundManager = GameObject.FindGameObjectWithTag("SoundManager");
	}
	
	// Update is called once per frame
	void Update () {
	
	}

    public void StopCountdown() {
        if (coroutine != null) StopCoroutine(coroutine);
        textMesh.GetComponent<TextController>().FadeOut(false);
    }

    public void StartCountdown(int time) {
        if (coroutine != null) StopCountdown();

        coroutine = Countdown(time);
        StartCoroutine(coroutine);
    }

    IEnumerator Countdown(float time) {
        textMesh.GetComponent<TextController>().FadeIn("" + time);
        int lastTime = (int)time;

        while (time > 0) {
            int roundTime = (int)time;

            if (roundTime != lastTime) {
                if (roundTime % 2 == 0) {
                    SoundUtils.playSound(soundManager, clock1, clockVolume);
                }
                else SoundUtils.playSound(soundManager, clock2, clockVolume);

                lastTime = roundTime;
            }

            textMesh.text = "" + roundTime;
            time -= Time.deltaTime;

            yield return null;
        }

        // Change game state
        textMesh.text = "";
        textMesh.GetComponent<TextController>().FadeOut(false);
        GameManager.SetGameState(GameManager.State.Lose);
    }
}
