using UnityEngine;
using System.Collections;

public class BoxClickerScript : MonoBehaviour {
	
	public GameObject[] boxes;
	private int highlightedbox = -1;
	
	
	public Material litmat;
	public Material blahmat;
	public Material flashmat;
	
	public TextMesh screenText;
	public TextMesh scoreText;
	public TextMesh recordText;
	
	private int score =0;
	private int record =0;
	
	private bool playing = false;
	
	private float timeLeft = 0f;
	
	// Use this for initialization
	void Start () {
		record = PlayerPrefs.GetInt("BoxClickerRecord",0);
	}
	
	// Update is called once per frame
	void Update () {
		
		if (Input.GetKeyDown("escape")) Application.LoadLevel(0);
		
		scoreText.text = "Score:\n" + score.ToString();
		recordText.text = "Record:\n" + record.ToString();
		
		
		for (int i=0; i<boxes.Length; i++){
			if (i ==highlightedbox){
				boxes[i].renderer.material = litmat;
			}else{
				boxes[i].renderer.material = blahmat;
			}
			
		}
		
		
		if (!playing){
			screenText.text = "Press Space to begin!";
			if (Input.GetKeyDown("space")){
				playing = true;
				timeLeft = Time.time + 10f;
				highlightedbox = Random.Range(0,3);
				score = 0;
			}
		}
		if (playing){
			screenText.text = Mathf.Round(timeLeft-Time.time).ToString();
			
			
			Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
			RaycastHit mouseHit = new RaycastHit();
			if (boxes[highlightedbox].collider.Raycast(mouseRay, out mouseHit,99f)){
				if (Input.GetKeyDown("mouse 0")){
					
					boxes[highlightedbox].renderer.material = flashmat;
					
					highlightedbox = Random.Range(0,3);
					score++;
					
				}
			}
			
			
			if (score>record){
				record = score;
				PlayerPrefs.SetInt("BoxClickerRecord",record);
			}
			
			
			
			if (Time.time> timeLeft){
				playing = false;
				highlightedbox = -1;
			}
			
			
			
		}
		
		
		
	}
}
