using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour {

	public int currentPerspective = 0;
	public int maxPerspective = 3;

	private GameObject[] Objects;
	private GameObject eventSheet;
	private bool[] isFirst = new bool[]{true, true, true, true};

	void Awake() {

		// Set render off for all perspective objects
		for(int i = 1; i <= maxPerspective; i++)
		{
			Objects = GameObject.FindGameObjectsWithTag("Perspective"+i);
			Render (Objects, false);
		}

		// Render All in Perspective 4
		Objects = GameObject.FindGameObjectsWithTag("Perspective4");
		Render (Objects, true);

		// Define EventSheet
		eventSheet = GameObject.FindGameObjectWithTag("EventSheet");

		// On Start check perspective. Make sure at least in first and not more than the max
		if(currentPerspective < 1 || currentPerspective > maxPerspective)
		{
			currentPerspective = 1;
		}
	}

	void Update () {

		// Render what needs to be rendered
		Objects = GameObject.FindGameObjectsWithTag("Perspective"+currentPerspective);
		Render(Objects, true);

		// If first time in current Perspective perform this
		if(isFirst[currentPerspective])
		{
			eventSheet.GetComponent<EventSheet>().BroadcastMessage("firstPerspective"+currentPerspective);
			isFirst[currentPerspective] = false;
		}

		// Iterate through the perspectives.
		// NB must be moved to the player script
		if(Input.GetKeyDown(KeyCode.Z))
		{
			// haha C++
			currentPerspective++;

			// Making sure to reset when max reached.
			if(currentPerspective > maxPerspective)
			{
				currentPerspective = 1;
			}

			// Switch Lights
			SwitchLight ();

			// Turn off everything in current perspective.
			Render(Objects, false);
		}
	}

	// Render function.
	public void Render (GameObject[] Objects, bool active)
	{
		if(active)
		{
			foreach (GameObject thing in Objects)
			{
				thing.renderer.enabled = true;
				thing.collider.isTrigger = false;
			}
		}
		else
		{
			foreach (GameObject thing in Objects)
			{
				thing.renderer.enabled = false;
				thing.collider.isTrigger = true;
				thing.light.enabled = false;
			}
		}

	}

	public void SwitchLight ()
	{
		for (int i = 1; i <= maxPerspective; i++ )
		{
			GameObject.Find("Perspective" + i + "Light").GetComponent<LightController>().On = false;
		}
		GameObject.Find("Perspective" + currentPerspective + "Light").GetComponent<LightController>().On = true;
	}

}
