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

[RequireComponent(typeof(PhysicsEngine))]
public class RocketEngine : MonoBehaviour {

	public float fuelMass;				// [kg]
	public float maxThrust; 			// kN [kg*m/s^2]
	[Range (0f, 1f)]
	public float thrustPercent;			// [dimensionless]
	public Vector3 thrustUnitVector; 	// [dimensionless]

	private PhysicsEngine pe;
	private float currentThrust; 		// N

	// Use this for initialization
	void Start () {
		pe = GetComponent<PhysicsEngine>();
		pe.mass += fuelMass;
	}
	
	void FixedUpdate () {
		if (fuelMass > FuelThisUpdate()) {
			fuelMass -= FuelThisUpdate();
			pe.mass -= FuelThisUpdate();
			ExertForce();
		} else {
			//Debug.LogWarning("Out of rocket fuel");
		}
	}

	private float FuelThisUpdate() {
		float exhastMassFlow; // [kg/s]
		float effectiveExhastVelocity = 4462; // [m/s]

		exhastMassFlow = currentThrust / effectiveExhastVelocity;

		return exhastMassFlow * Time.deltaTime; // [kg]
	}

	private void ExertForce() {
		currentThrust = thrustPercent * maxThrust * 1000f;
		Vector3 thrustVector = thrustUnitVector.normalized * currentThrust;
		pe.AddForce(thrustVector);
	}
}
