using UnityEngine;
using System.Collections;

public class Controls : MonoBehaviour
{
	#region Update

	private void Update()
	{
		UpdateInput();
		UpdateAnimation();
	}

	#endregion

	#region Input

	private Vector3 MovementInput;
	private Vector3 MovementDirection;
	private int JumpState;

	private void UpdateInput()
	{
		ResetInput();

		MovementInput.x += Input.GetAxis("Horizontal");
		MovementInput.z += Input.GetAxis("Vertical");
		MovementInput.y += Input.GetButton("Jump") ? 1f : 0f;
		if (JumpState == 0 && MovementInput.y > 0f)
		{
			JumpState = 1;
		}
		if (JumpState == 2 && MovementInput.y == 0f)
		{
			JumpState = 0;
		}

		if (MovementInput.magnitude > 0.1f)
		{
			MovementDirection = MovementInput.normalized;
		}
	}

	private void ResetInput()
	{
		MovementInput = Vector3.zero;
	}

	#endregion

	#region Dynamics

	public float InitialJumpForce = 10f;
	public float JumpForce = 1f;
	public float MovementSpeed = 1f;
	public float HorizontalDamping = 0.03f;

	private void FixedUpdate()
	{
		// Camera direction
		var cameraDirection = Quaternion.Euler(0f, Camera.main.transform.rotation.eulerAngles.y, 0f);

		// Horizontal movement
		var horizontalMovementInput = MovementInput;
		horizontalMovementInput.y = 0;
		var deltaVelocity = cameraDirection * (horizontalMovementInput * MovementSpeed);

		// Jump
		deltaVelocity.y += MovementInput.y * JumpForce;
		if (JumpState == 1)
		{
			//Game.Instance.PlayerCharacter.ShowBalloon("Jump!");
			JumpState = 2;
			deltaVelocity.y += InitialJumpForce;
		}

		// Apply
		rigidbody.AddForce(deltaVelocity, ForceMode.VelocityChange);

		// Horizontal damping
		var horizontalVelocity = rigidbody.velocity;
		horizontalVelocity.y = 0f;
		rigidbody.AddForce(horizontalVelocity * -HorizontalDamping);
	}

	#endregion

	#region Animation

	public Animator Animator;

	private void UpdateAnimation()
	{
		var speed = rigidbody.velocity.magnitude;
		Animator.SetFloat("Speed", speed);
	}

	#endregion
}
