using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour {

	Transform thisTF;
	Rigidbody thisRB;
	SailSpeed thisSail;
	[SerializeField] MakeFlamesGonzo flames;


	bool isBoosted;
	public bool isOpen;
	[SerializeField] LayerMask boostMask;

	[SerializeField] float solarPower;
	[SerializeField] AnimationCurve solarCurve;
	[SerializeField] float maxSolarSpeed;

	[SerializeField] float thrusterSpeed;
	[SerializeField] AnimationCurve thrusterCurve;
	[SerializeField] float maxThrusterSpeed;
	[SerializeField] float rotsSpeed;

	void Start () {
		thisTF = GetComponent<Transform> ();
		thisRB = GetComponent<Rigidbody> ();
		thisSail = GetComponent<SailSpeed> ();
	}



	void Update () {

		isOpen = Physics.CheckBox (thisTF.position, Vector3.one, thisTF.rotation, boostMask);
		GetComponent<Animator> ().SetBool ("isOpen", isOpen);



		Vector2 move = new Vector2 (Input.GetAxis ("Horizontal"), Input.GetAxis ("Vertical"));
		float velocity = thisRB.velocity.magnitude;		

		//rotate
		thisTF.rotation = Quaternion.Slerp(thisTF.rotation, Quaternion.LookRotation(Vector3.forward + Vector3.right * move.x), 0.1f + 0.7f*Mathf.Abs(move.y));

		//forward
		float relativeThruster = 0f;
		if (velocity > maxThrusterSpeed)
			relativeThruster = 0f;
		else
			relativeThruster = thrusterCurve.Evaluate (velocity / maxThrusterSpeed);
		
		if(move.y > -0.01f)
			thisRB.AddForce (thisTF.forward * 1 * Time.deltaTime * thrusterSpeed * relativeThruster);



		float relativeSolar = 0f;
		if (velocity > maxSolarSpeed)
			relativeSolar = 0f;
		else
			relativeSolar = solarCurve.Evaluate (velocity / maxSolarSpeed);

		if (thisSail.speed > 0f && !isBoosted) 
		{
			isBoosted = true;
			flames.MakeVisible ();
		} 
		else if(thisSail.speed <=0f && isBoosted)
		{
			isBoosted = false;
			flames.MakeInvisible ();

		}	

		thisRB.AddForce (thisTF.forward * thisSail.speed * Time.deltaTime * solarPower * relativeSolar);

	}
}
