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

public class LayerManager : MonoBehaviour {

	Dictionary<string, int> layerPositions;
	string[] keys = {"red", "blue", "green", "yellow"};

	// Use this for initialization
	void Start () {
		layerPositions = new Dictionary<string, int>();
		layerPositions.Add (keys[0], 0);
		layerPositions.Add (keys[1], 1);
		layerPositions.Add (keys[2], 2);
		layerPositions.Add (keys[3], 3);
	}
	
	// Update is called once per frame
	void Update () {
		//Take input to switch the layer order
		if(Input.GetKeyDown(KeyCode.UpArrow) || Input.GetButtonDown ("SwapUp")){
			shiftLayersUp();
		}
		else if(Input.GetKeyDown(KeyCode.DownArrow)|| Input.GetButtonDown ("SwapDown")){
			shiftLayersDown();
		}

		//Face buttons
		if(Input.GetButtonDown ("Red")){
			jumpToTop("red");
		}
		else if(Input.GetButtonDown ("Blue")){
			jumpToTop("blue");
		}
		else if(Input.GetButtonDown ("Green")){
			jumpToTop("green");
		}
		else if(Input.GetButtonDown ("Yellow")){
			jumpToTop("yellow");
		}
	}

	private void shiftLayersUp(){
		foreach(string s in keys){
			layerPositions[s] ++;
			if(layerPositions[s] == layerPositions.Count){
				layerPositions[s] = 0;
			}
		}
		//if(!audio.isPlaying){
			audio.Play();
		//}
	}

	private void shiftLayersDown(){
		foreach(string s in keys){
			layerPositions[s] --;
			if(layerPositions[s] < 0){
				layerPositions[s] = layerPositions.Count - 1;
			}
		}
		//if(!audio.isPlaying){
			audio.Play();
		//}
	}

	private void jumpToTop(string color){
		while(layerPositions[color] != layerPositions.Count-1){
			shiftLayersUp ();
		}
	}

	public int getLayerPosition(string layerName){
		if(layerName == ""){
			Debug.LogError ("layerName is blank. Please provide color.");
		}
		return layerPositions[layerName];
	}

	public string getTopLayerName(){
		foreach(string s in keys){
			if(layerPositions[s] == layerPositions.Count-1){
				return s;
			}
		}
		return null;
	}
}
