using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody))]
public class Trick_SpinSensor : MonoBehaviour 
{
	public Rigidbody rb;
	public float angularVelocityRequirement			= 360;
	public float angularVelocityRequirement_soft	= 180;
	public bool trick								= false;
	public float cooldown 							= 0.5f;
	public float max_cooldown						= 0.5f;

	public float degrees;
	public float minDegrees							= 180;
	public float minDegreesToSucceed				= 360;

	public float maxAngularVelocity					= 7;

	public float scorePerDegree						= 0.25f;

	void Start()
	{
		rb = GetComponent<Rigidbody> ();
		rb.maxAngularVelocity = maxAngularVelocity;
	}

	void Update()
	{
		cooldown = Mathf.Max(0, cooldown - Time.deltaTime);
	}

	void FixedUpdate()
	{
		float angularVelocity = Mathf.Rad2Deg * rb.angularVelocity.magnitude;

		if (trick) 
		{
			if (angularVelocity >= angularVelocityRequirement_soft) {
				degrees += angularVelocity * Time.fixedDeltaTime;
				ScoreManager.SetTrickName ("Spinout " + degrees.ToString ("F0") + " degrees");
				ScoreManager.SetTrickScore (degrees * scorePerDegree);
				//ScoreManager.RefreshTrick ();

				cooldown = max_cooldown;
			} else {

				if (degrees < minDegreesToSucceed)
				{
					ScoreManager.FailTrick();
					degrees = 0;
					trick = false;
					cooldown = max_cooldown;
				}
				else
				{
					ScoreManager.EndTrick ();
					degrees = 0;
					trick = false;
					cooldown = max_cooldown;
				}
			}
		} 
		else 
		{
			if (angularVelocity >= angularVelocityRequirement) {
				degrees += angularVelocity * Time.fixedDeltaTime;

				if (cooldown <= 0 && degrees >= minDegrees) {
					trick = true;
					ScoreManager.NewTrick ("Spinout", 0, 0, 0);
				}

			} else {
				degrees = 0;
			}
		}
	}
}
