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

public class Scorecanvas : MonoBehaviour {

	float lastTime;

	int secondsleft;
	bool alive;

	Globals g;

	// Use this for initialization
	void Start () {
		lastTime = 0;
		alive = true;

		if (null != GameObject.Find("Halp"))
		{
			alive = false;
		}

		g = FindObjectOfType(typeof(Globals)) as Globals;

		this.transform.Find("score").GetComponent<UnityEngine.UI.Text>().text = 
			System.String.Format ("${0}",g.monies);

		if (g.difficulty == 0)
			secondsleft = 300;
		else
		{
			secondsleft = (int)(300*Mathf.Pow(g.difficulty/2.0f,-0.5f));
		}

		this.transform.Find("score").GetComponent<UnityEngine.UI.Text>().text = 
			System.String.Format ("${0}",g.monies);

		string seconds = System.String.Format("{0}:{1:00}",secondsleft/60,secondsleft%60);
		transform.Find ("time").GetComponent<UnityEngine.UI.Text>().text = seconds;
	}
	
	// Update is called once per frame
	void Update () {
		if (!alive)
			return;

		if (Input.GetKeyDown (KeyCode.Escape))
		{
			alive = false;
			g.failBox();
		}

		if ((int)Time.time > lastTime)
		{
			lastTime = Time.time;
			secondsleft--;

			string seconds = System.String.Format("{0}:{1:00}",secondsleft/60,secondsleft%60);
			transform.Find ("time").GetComponent<UnityEngine.UI.Text>().text = seconds;

			if (secondsleft <= 0)
			{
				alive = false;
				g.failBox();
			}

			Target[] targets = FindObjectsOfType (typeof(Target)) as Target[];
			bool allValid = true;
			foreach (Target t in targets)
			{
				allValid = allValid && t.Pass ();
			}

			if (allValid)
			{
				alive = false;
				g.winBox();
			}

		}
	}
}
