using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using Alcatraz;

namespace Alcatraz
{
	[RequireComponent(typeof(MainController))]
	public class TimeManager : MonoBehaviour
	{
		public float gameSeconds = 60f;
		public float delayStartSeconds = 3f;
		public Text timeText;

 		float currentGameTime { get; set;}

		private MainController m_mainController;
		private bool isStart = false;

		void Awake() {
			currentGameTime = gameSeconds;
			StartCoroutine ( CountDownAndGameStart() );
		}

		void Start() {
			// set initial display time
			timeText.text = convertTimeDisplay (gameSeconds);

			// get reference of MainController
			m_mainController = GetComponent<MainController> ();
		}

		IEnumerator CountDownAndGameStart() {
			yield return new WaitForSeconds (delayStartSeconds);
			m_mainController.SendMessage ("OnGameStart");
			isStart = true; 
		}

		void FixedUpdate (){
			if (isStart) {
				currentGameTime -= Time.fixedDeltaTime;
				checkGameTime ();
				timeText.text = convertTimeDisplay(currentGameTime);
			}
		}

		string convertTimeDisplay (float seconds) {
			return string.Format("{0:f2} ", seconds).Replace(".", "\"");
		}

		void checkGameTime () {
			if ( 0 >= currentGameTime ) {
				m_mainController.SendMessage("OnTimeUp");
				currentGameTime = 0f;
				isStart = false;
			}
		}
	}
}