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

public class Player : MonoBehaviour {

	public Transform menu;
	public static Player instance;
	List<GameObject> list = new List<GameObject>();
	float timer = 0f;
	
	public AudioSource footSteps;
	
	// Use this for initialization
	bool isLocked = true;
	
	void Awake () {
		instance = this;
	}
	
	void Start () {
		Invoke ("Unlock", 3f);
	
	}
	
	void Unlock () {
		isLocked = false;
	}
	
	// Update is called once per frame
	void LateUpdate () {
		if (HudController.instance.isGameOver || isLocked) return;
		if (transform.localEulerAngles.x < 30f || transform.localEulerAngles.x > 100f) {
			if (!HudController.instance.menuShown) {
				transform.Translate(new Vector3(0,0,Time.deltaTime * 2f));
				if (!footSteps.isPlaying)
					footSteps.Play();
			}
		}
		else if (!HudController.instance.menuShown) {
			if (footSteps.isPlaying)
				footSteps.Stop();
			
			if (timer > 1f) {
				timer = 0f;
				if (list.Count > 0) {
					GameObject o = list[list.Count - 1];
					o.gameObject.SetActive(true);
					o.GetComponent<BoxCollider>().isTrigger = false;
					Vector3 p = transform.position;
					p = p + transform.TransformDirection(Vector3.forward) * 1f;
					p.y = 5.5f;
					o.transform.position = p;
					list.RemoveAt(list.Count - 1);
					AudioManager.instance.Play (Sounds.Create, transform);
					
					
				}				
				HudController.instance.hasPieces.gameObject.SetActive((list.Count >0 )? true : false);
				
			} else {
				timer += Time.deltaTime;
			}
		} else {
			if (footSteps.isPlaying)
				footSteps.Stop();
		}
		
		menu.position = transform.position;
		float euler = transform.localEulerAngles.y;
		Vector3 e = menu.localEulerAngles;
		e.y = euler;
		menu.localEulerAngles = e;
		
		
	}
	
	void OnTriggerEnter ( Collider col){
		if (HudController.instance.isGameOver) return;
		
		if (col.tag == "Barricade") {	
			AudioManager.instance.Play (Sounds.Pickup, transform);	
			list.Add (col.gameObject);			
			col.gameObject.SetActive(false);
			print ("Collect item");
			HudController.instance.hasPieces.gameObject.SetActive(true);
		} else if (col.tag == "Save") { 
			HudController.instance.GameWin();
		} else if (col.tag == "Key") { 
			col.gameObject.SetActive(false);
			AudioManager.instance.Play (Sounds.Pickup, transform);	
			HudController.instance.GetKey();
		} 
		else if (col.tag == "HoldCell" && HudController.instance.HasKey) { 
			HudController.instance.HasKey = false;
			HudController.instance.holdCell.gameObject.SetActive(false);
			HudController.instance.hudKey.gameObject.SetActive(false);
			AudioManager.instance.Play (Sounds.Create,HitAim.instance.currNpc);
		}	
	}
}
