using UnityEngine;
using System.Collections;

public class MazeRotationController : MonoBehaviour {

	public static bool rotating = false;
	public static bool rotationAllowed = true;

	private int _rotationsRemaining = 60;

	public GameObject rotGUI;
	public GameObject player;

	private float speed = 6;
	private int destinationAngle = 0;
	private bool movePlayerAllowed = true;
	//private float rotationBuffer = .05f;
	private float timer = 0;
	private float delay = .6f;
	public static float[] anglesArr;
	// Use this for initialization
	void Start () {
			
			// create the array and set it's rotation angles
		anglesArr = new float[4];
		anglesArr[0] = 0f;
		anglesArr[1] = 90f;
		anglesArr[2] = 180f;
		anglesArr[3] = 270f;

		rotGUI.guiText.text = "Rotations :" + _rotationsRemaining;
	}
	
	// Update is called once per frame
	void Update () {
			
			// set the destination angle of the maze based on player input
		if( Input.GetButtonDown("Fire1") && rotationAllowed && _rotationsRemaining > 0)
		{
			rotating = true;
			destinationAngle ++;
			timer = delay;
			movePlayerTowardsCenter();
		}

		if( Input.GetButtonDown("Fire2") && rotationAllowed  && _rotationsRemaining > 0)
		{
			rotating = true;
			destinationAngle --;
			timer = delay;
			movePlayerTowardsCenter();
		}

			// catch out of range errors and 'wrap' them
		if( destinationAngle < 0 )
			destinationAngle = 3;

		if( destinationAngle > 3 )
			destinationAngle = 0;

			// Slerp to the destination angle.. Yes this is constantly running even if the angle doesn't change. I don't want to spend the time to figure out a more robust system..
		transform.rotation = Quaternion.Slerp( transform.rotation, Quaternion.Euler(0,0,anglesArr[destinationAngle]) , speed * Time.deltaTime );

			// rotating is over afer this timer has elapsed
		timer -= Time.deltaTime;
		if ( timer < 0 && rotating)
		{	
				// at this point no more rotation is allowed, and this counts as the end of one rotation 'session'
			rotating = false;
			_rotationsRemaining--;
			rotGUI.guiText.text = "Rotations :" + _rotationsRemaining;
			
			movePlayerAllowed = true;
			if( timer > -.5f )
				rotationAllowed = false;
		}
	}

		// This method is intended to be called only when the player has landed on the ground. That is how I am limiting one rotation session per jump.
	public void allowRotation()
	{
		rotationAllowed = true;
	}

	private void movePlayerTowardsCenter()
	{
		if(movePlayerAllowed)
		{
			Vector3 vec = new Vector3(0,0,player.transform.position.z);
			player.transform.position = Vector3.MoveTowards(player.transform.position, vec , .7f);
		}
		movePlayerAllowed = false;
	}

	public int rotationsRemaining
	{
		get{
			return _rotationsRemaining;
		}
		set{
			_rotationsRemaining = value;
			rotGUI.guiText.text = "Rotations :" + _rotationsRemaining;
		}
	}




}
