using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

	private const float frameFirstStep = 7f;
	private const float frameSecondStep = 17f;

	public AudioClip[] walkSounds;

	private float speed = 8f;
	//public Text pickUpObject;

	public float velo;
	public Animator anim;
	public AudioSource walkSound;
	public static float direction;

	void Update () {
		velo = GetComponent<Rigidbody> ().velocity.magnitude;

		anim.SetFloat ("Velocity", velo);
		float rot = -999f;
		if (Input.GetKey (KeyCode.A) && Input.GetKey (KeyCode.W)) {
			rot = 45f;
		} else if (Input.GetKey (KeyCode.W) && Input.GetKey (KeyCode.D)) {
			rot = 315f;
		} else if (Input.GetKey (KeyCode.D) && Input.GetKey (KeyCode.S)) {
			rot = 225f;
		} else if (Input.GetKey (KeyCode.S) && Input.GetKey (KeyCode.A)) {
			rot = 135f;
		} else if(Input.GetKey (KeyCode.A))
		{
			rot = 90f;
		} else if (Input.GetKey (KeyCode.W)) {
			rot = 0f;
		} else if (Input.GetKey (KeyCode.D)) {
			rot = 270f;
		} else if (Input.GetKey (KeyCode.S)) {
			rot = 180f;

		} else {
			return;
		}
		rot = rot + 45f;

		transform.rotation = Quaternion.Euler(new Vector3(0,(-rot + 90f),0));
		direction = rot;
		float xs = Mathf.Cos(rot * Mathf.Deg2Rad) * speed;
		float ys = Mathf.Sin(rot * Mathf.Deg2Rad) * speed;
		GetComponent<Rigidbody>().AddForce(new Vector3(xs,0,ys));

		if (((int)anim.GetCurrentAnimatorStateInfo (0).normalizedTime * 22f) == frameFirstStep ||
		   ((int)anim.GetCurrentAnimatorStateInfo (0).normalizedTime * 22f) == frameSecondStep) {
			walkSound.enabled = false;
			walkSound.clip = walkSounds [(int) Random.Range(0f, 5.99f)];
			walkSound.enabled = true;
		}
	}
}
