using UnityEngine;
using System.Collections;

public class Checkpoints : MonoBehaviour {

	public Transform playerTransform;
	private float time = 0;
	
	private bool isRunning = false;
	private bool isFinished = false;

	void  Start (){
		isRunning = true;
		isFinished = false;

		playerTransform = GameObject.FindWithTag("Player").transform;
	}
	
	void Update () {
		if(isRunning)
			time += Time.deltaTime;
	}

	void  OnTriggerEnter ( Collider other  ){
		
				if (!other.CompareTag ("Player")) 
						return;
		
		
				if (transform == playerTransform.GetComponent<CarCheckpoint> ().checkPointArray [CarCheckpoint.currentCheckpoint].transform) {
			
						if (CarCheckpoint.currentCheckpoint + 1 < playerTransform.GetComponent<CarCheckpoint> ().checkPointArray.Length) {
								if (CarCheckpoint.currentCheckpoint == 0)
										CarCheckpoint.currentLap++;
								CarCheckpoint.currentCheckpoint++;
						} else {
								CarCheckpoint.currentCheckpoint = 0;
						}

						if (CarCheckpoint.currentLap > 1) {
								FinishedGame ();
						}

						// GUI update
						if (isRunning) {
								Camera.main.GetComponentInChildren<TextMesh> ().text = "Checkpoint: " + (CarCheckpoint.currentCheckpoint);		
						}
				}
		}

	void OnGUI() {
		if(isFinished) {
			GUI.Box(new Rect(Screen.width / 2 - 65, 185, 200, 50), "Koniec gry");
			GUI.Label(new Rect(Screen.width / 2 - 10, 200, 200, 50), "Czas okrążenia " + ((int)time).ToString() + "s");
		}
	}

	public void FinishedGame()
	{
		isRunning = false;
		isFinished = true;
	}
}
