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

public class GameController : MonoBehaviour {
	public Text inventory;
	public Text winText;
	public Text warnText;
	private bool hasSkillet;
	private bool hasEggs;
	private bool hasSpatula;

	private string winMessage;
	private string warnMessage;

	private float warnTimer;
	private float creditsTimer;

	public Transform eggs;
	
	// Use this for initialization
	void Start () {
		Screen.showCursor = false;
		Screen.lockCursor = true;
		hasSkillet = false;
		hasEggs = false;
		hasSpatula = false;

		winMessage = winText.text;
		winText.text = "";

		warnMessage = warnText.text;
		warnText.text = "";
		warnTimer = 0;

		creditsTimer = 0;

		if (eggs) {
			for(int i = 0; i < 500; i++){
				GameObject egg = (Instantiate(eggs, new Vector3(Random.Range (-50, 50), 6.25f, Random.Range (-50, 50)), Quaternion.identity) as Transform).gameObject;
				egg.transform.Rotate(Vector3.up * Random.value * 360);
			}
		}
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetKey("escape"))
			Application.LoadLevel (0);
		if (Input.GetMouseButton (0) || Input.GetMouseButton (1)) {
			Vector3 fwd = transform.TransformDirection (Vector3.forward);
			RaycastHit hit;
			if(Physics.Raycast(transform.position, fwd, out hit, 15.0f)){
				string tag = hit.collider.gameObject.tag;
				Rigidbody rb = hit.collider.gameObject.GetComponent<Rigidbody>();
				if(!hasSkillet && tag == "skillet"){
					hasSkillet = true;
					hit.collider.gameObject.SetActive(false);
					addInventoryItem("Skillet");
				}
				else if(!hasEggs && tag == "eggs"){
					hasEggs = true;
					hit.collider.gameObject.SetActive(false);
					addInventoryItem("Eggs");
				}
				else if(!hasSpatula && tag == "spatula"){
					hasSpatula = true;
					hit.collider.gameObject.SetActive(false);
					addInventoryItem("Spatula");
				}
				else if(tag == "stove"){
					if(hasSkillet && hasEggs && hasSpatula){
						inventory.text = "";
						winText.text = winMessage;
						creditsTimer = 5;
					}
				}
				else if(rb){
					if(Input.GetMouseButton (1)){
						fwd *= -1;
					}
					rb.AddForce(fwd * 250);
					rb.AddForce (Vector3.up*200);
					rb.useGravity = true;
					rb.constraints = 0;

					warnText.text = warnMessage;
					warnTimer = 3;

					if(!GetComponents<AudioSource>()[1].isPlaying){
						GetComponents<AudioSource>()[1].Play ();
					}
				}
			}
		}

		if (warnText.text.Length > 0 && warnTimer > 0) {
			warnTimer = warnTimer - Time.deltaTime;
		}
		if (warnTimer <= 0) {
			warnText.text = "";
		}

		if (creditsTimer > 0) {
			creditsTimer = creditsTimer - Time.deltaTime;
			if(creditsTimer <= 0){
				Application.LoadLevel (2);
			}
		}
	}
	
	void addInventoryItem(string item){
		if (inventory.text.Length == 0) {
			inventory.text = "Inventory:";
		}
		inventory.text += "\n- " + item;
	}
}
