using UnityEngine;
using System.Collections;

public class ClueActivator : MonoBehaviour {

	public int eventLayer = 0;
	public string eventToCall;
	public new bool active;
	public bool eventAdd;
	public bool hasEventToRun;

	private GameObject EventSheet;
	private int currentEvent;
	private bool turnOff = false;


	void Start () {

		// Destroy if no eventLayer given and its adding to the event squence
		if(eventLayer <= 0 && eventAdd)
			GameObject.Destroy(this.gameObject);

		// Destroy if no eventToCall but hasEventToRun
		if(eventToCall == "" && hasEventToRun)
			GameObject.Destroy(this.gameObject);

		EventSheet = GameObject.FindGameObjectWithTag("EventSheet");



	}

	void Update ()
	{
		// See if the current eventController is active.
		active = transform.parent.gameObject.GetComponent<EventController>().active;

		// Get the current currentEvent from the event controller 
		currentEvent = transform.parent.gameObject.GetComponent<EventController>().currentEvent;

		// If this is the current clue highlight with spot light
		if((eventLayer != 0 && eventLayer == currentEvent && this.gameObject.renderer.enabled && active)||(eventLayer == 0 && this.gameObject.renderer.enabled && active && !turnOff))
			light.enabled = true;
		else
			light.enabled = false;
	}

	void OnTriggerEnter (Collider other)
	{
		// Get the current currentEvent from the event controller 
		currentEvent = transform.parent.gameObject.GetComponent<EventController>().currentEvent;

		// If the collider is the player and the current event == the event layer display the clue
		if(other.tag == "Player" && eventLayer == currentEvent && this.gameObject.renderer.enabled == true && active)
		{
			// Increase Current Event by 1.
			if(eventAdd)
				transform.parent.gameObject.GetComponent<EventController>().currentEvent++;
			// Run Event.
			if(hasEventToRun)
				EventSheet.GetComponent<EventSheet>().BroadcastMessage(eventToCall);
				
			this.audio.Play ();
		}
		else if(other.tag == "Player" && eventLayer == 0 && this.gameObject.renderer.enabled == true && active && !turnOff)
		{
			// Run Event.
			if(hasEventToRun)
				EventSheet.GetComponent<EventSheet>().BroadcastMessage(eventToCall);

			this.audio.Play ();
			turnOff = true;
		}
	}	
}
