using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour {
	public Rigidbody Body;
	public float TurnForce = 10f;
	public bool isDead = false;
	public float TimeSplitter = 3f;

	void Start(){
		Body = gameObject.GetComponent<Rigidbody> ();
	}

	// Update is called once per frame
	void FixedUpdate () {
		if (!isDead) {
			Body.AddForce (Vector3.right);
		}
	}

	void Update(){
		if(Input.GetKey(KeyCode.UpArrow)){
			Body.AddForce(Vector3.up * TurnForce);
		}

		if(Input.GetKey(KeyCode.DownArrow)){
			Body.AddForce(Vector3.down * TurnForce);
		}

		if (Input.GetKey (KeyCode.Space)) {
			if(TimeSplitter > 0f){
				Time.timeScale = 0.5f;
				TimeSplitter -= Time.deltaTime;

				if(TimeSplitter < 0f){
					TimeSplitter = 0f;
				}
			}else{
				TimeSplitter = 0f;
				Time.timeScale = 1f;
			}
		}

		if (Input.GetKeyUp (KeyCode.Space)) {
			Time.timeScale = 1f;
		}
	}

	void OnGUI(){
		GUILayout.BeginArea (new Rect (10, Screen.height-75, 200, 100));
		GUILayout.Label ("Speed: " + gameObject.GetComponent<Rigidbody>().velocity.x.ToString("N"));
		GUILayout.Label ("Distance: " + transform.position.x.ToString("N"));
		GUILayout.Label ("Time Splitter: " + TimeSplitter.ToString("N"));
		GUILayout.EndArea ();
	}

	void OnTriggerEnter(Collider col){
		if (col.tag == "Enemy") {
			//We died! Stop the game!
			KillPlayer();
		}

		if (col.tag == "Pickup") {
			//Performe pickup
			AddPickup(col.gameObject);
		}
	}

	void AddPickup(GameObject pickup){
		TimeSplitter += 1f;
		Destroy (pickup);
	}

	void KillPlayer(){
		//Remove all effects
		Body.velocity = Vector3.zero;
		GetComponent<GameController> ().enabled = false;
		isDead = true;
		GUIController.gui.isPlayerDead = true;
		GUIController.gui.Score = transform.position.x;
	}
}
