using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

	public GameObject mazeRoot;

	private float speed = 18f;
	private float jumpSpeed = .5f;
	private float gravity = 1.5f; //9.8f;
	private float vSpeed = 0f;

	private CharacterController cc;
	private float xMovement = 0;
	private bool jumping = true;

	public AudioClip[] playerSounds;

	// Use this for initialization
	void Start () {
		cc = GetComponent<CharacterController>();
	}
	
	// Update is called once per frame
	void Update () {

			// if the maze is NOT rotating
		if( !MazeRotationController.rotating )
		{	
				// set the horizontal speed based on the player input keys
			xMovement = Input.GetAxis ("Horizontal") * speed * Time.deltaTime;

				// stop vertical movement if already on the ground uless jump is pressed
			if( cc.isGrounded )
			{
				vSpeed = 0f;
				jumping = false;
				if(Input.GetButton("Jump"))
				{
					vSpeed = jumpSpeed;
					jumping = true;
					//print ( "jumping: " + vSpeed);

					AudioSource.PlayClipAtPoint(playerSounds[0],transform.position,100f);
				}

					// This ensures that only one rotation is allowed per jump
				mazeRoot.GetComponent<MazeRotationController>().allowRotation();
				//MazeRotationController.rotationAllowed = true;
			}
			else
			{		// apply gravity
				vSpeed -= gravity * Time.deltaTime;
			}
						
				// move the player
			cc.Move ( new Vector3(xMovement, vSpeed, 0) );
		}

		transform.eulerAngles = new Vector3( -mazeRoot.transform.eulerAngles.x,0,0);
	}

	void OnControllerColliderHit( ControllerColliderHit hit )
	{
		//
		//AudioSource.PlayClipAtPoint(playerSounds[0], transform.position);
		//hit.collider.renderer.material.color = Color.blue;
		//vSpeed = 0;
		// here I can also check the transform of the hit object to see it's orientation etc..
	}

	void OnTriggerEnter(Collider other)
	{
		AudioSource.PlayClipAtPoint(playerSounds[1],transform.position,100f);
		GameObject.Find("GameManagerObject").GetComponent<GameManager>().hitGoal();
	}
}
