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

public class DoorOpener : MonoBehaviour {
	
	private string  state = "title";
	
	public string[] keys;
	private int currentdoorKey = 0;
	
	private float endTime = 0f;
	
	private int doorsOpened = 0;
	
	private int record = 0;
	
	public TextMesh textA;
	public TextMesh textB;
	public TextMesh textScore;
	public TextMesh textRecord;
	
	public GameObject doorPrefab;
	
	private GameObject door;
	private List<GameObject> doors = new List<GameObject>();
	
	private Vector3 targetPos;

	// Use this for initialization
	void Start () {
		record = PlayerPrefs.GetInt("DoorOpenerRecord", 0);
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetKey("escape")){
			Application.LoadLevel(0);
		}
		
		if (state == "title"){
			
			textA.text = "press Esc to quit";
			textB.text = "PRESS SPACE TO START!";
			textScore.text = doorsOpened.ToString();
			textRecord.text = record.ToString();
			
			
			
			if (Input.GetKey("space")){
				
				for (int i=0; i<doors.Count; i++){
					Destroy(doors[i]);
				}
				doors = new List<GameObject>();
				
				
				currentdoorKey = Random.Range(0, keys.Length);
				state = "play";
				endTime = Time.time + 30f;
				doorsOpened = 0;
				door = (GameObject)GameObject.Instantiate(doorPrefab);
				door.transform.position = (-Vector3.right * 2f) + (Vector3.forward*doorsOpened*5f);
				Color randCol = new Color();
				randCol.r = Random.Range(0.5f, 1f);
				randCol.g = Random.Range(0.5f, 1f);
				randCol.b = Random.Range(0.5f, 1f);
				foreach (Transform child in door.transform){
					child.renderer.material.SetColor("_Color", randCol);
				}
				
				doors.Add(door);
			}
			
		}else{
			
			
			textA.text = Mathf.Round(endTime - Time.time).ToString();
			textB.text = "PRESS " + keys[currentdoorKey].ToUpper() + " !";
			textScore.text = "Doors: " + doorsOpened.ToString();
			textRecord.text = "Record: " + record.ToString();
			
			
			
			if (Input.GetKeyDown(keys[currentdoorKey])){
				doorsOpened++;
				currentdoorKey = Random.Range(0, keys.Length);
				
				
				//door.transform.eulerAngles = new Vector3(0,90,0);
				door.GetComponent<DoorOpenerScript>().Open();
				
				door = (GameObject)GameObject.Instantiate(doorPrefab);
				door.transform.position = (-Vector3.right * 2f) + (Vector3.forward*doorsOpened*5f);
				Color randCol = new Color();
				randCol.r = Random.Range(0.5f, 1f);
				randCol.g = Random.Range(0.5f, 1f);
				randCol.b = Random.Range(0.5f, 1f);
				foreach (Transform child in door.transform){
					child.renderer.material.SetColor("_Color", randCol);
				}
				
				doors.Add(door);
				
			}
			
			if (doorsOpened > record){
				record = doorsOpened;
				PlayerPrefs.SetInt("DoorOpenerRecord", record);
			}
			
			
			if (Time.time> endTime){
				state = "title";
			}
			
			
		}
	}
}
