using UnityEngine;
using System.Collections;

public class MainMenuManager : MonoBehaviour {

	private static MainMenuManager instance;
	
	public Follower cameraFollower;
	public Follower highlightFollower;
	public GameObject[] playerCandidates;
	public int index;

	[SerializeField]
	private string buttonNameLeft = "Left";
	[SerializeField]
	private string buttonNameRight = "Right";
	[SerializeField]
	private string buttonNameSelect = "Select";
	[SerializeField]
	private string buttonNameEscape = "Escape";

	[SerializeField]
	float secondsToHoldEscape = 1;
	[SerializeField]
	float secondsEscapeHeld	= 0;
	[SerializeField]
	GUIStyle escapeLabelStyle;

	public AudioClip swapSound;
	public AudioClip selectSound;


	void Awake()
	{
		instance = this;
		index = 0;
	}
	// Use this for initialization
	void Start () 
	{
		enabled = false;
	}
	
	// Update is called once per frame
	void Update () 
	{
		bool updateSelection = false;

		if (playerCandidates.Length == 0)
			return;


		if (Input.GetButtonDown (buttonNameLeft)) {
			AudioSource.PlayClipAtPoint(swapSound,Camera.main.transform.position,0.7f);
			index --;
			updateSelection = true;
		}
		if (Input.GetButtonDown (buttonNameRight)) {
			AudioSource.PlayClipAtPoint(swapSound,Camera.main.transform.position,0.7f);
			index ++;
			updateSelection = true;
		}
		if (Input.GetButtonDown (buttonNameSelect)) {
			AudioSource.PlayClipAtPoint(selectSound,Camera.main.transform.position,0.7f);
			SplashScreen.AddSummonAction(StartGame);
			SplashScreen.SetDismissTrigger(SplashScreen.DismissTrigger.DoneFadeIn);
			SplashScreen.Summon();
		}

		// Wraparounds.
		if (index >= playerCandidates.Length) {
			index = 0;
		}
		if (index < 0) {
			index = Mathf.Max(0, playerCandidates.Length -1);
		}

		if (updateSelection && playerCandidates[index] != null) {
			cameraFollower.target = playerCandidates[index];
			highlightFollower.target = playerCandidates[index];

			PersistData.get.selectedPlayerIndex = index;
			PersistData.get.wasPlayerSelectedFromMenu = true;
		}


		if (Input.GetButton (buttonNameEscape)) {
			secondsEscapeHeld += Time.deltaTime;
		} else {
			secondsEscapeHeld = 0;
		}
		
		if (secondsEscapeHeld >= secondsToHoldEscape) {
			foreach (Camera c in Camera.allCameras)
			{
				if (c != Camera.main)
					c.enabled = false;
			}
			Application.Quit();
		}
	}

	private static void StartGame()
	{
		GamesceneManager.ScheduleLoad(GamesceneManager.Actions.LoadMode,0);
	}
	public static void Enable()
	{
		instance.enabled = true;
	}

	void OnGUI()
	{
		if (secondsEscapeHeld > 0 && secondsEscapeHeld < secondsToHoldEscape) {
			string message = "Quitting in " + (secondsToHoldEscape - secondsEscapeHeld).ToString("F1") + " seconds.";
			
			GUI.Label(new Rect(
				0,0,
				Screen.width,
				Screen.height),
			          message,
			          escapeLabelStyle);
		}
	}
}


