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

public class PhysicsEngine : MonoBehaviour {

	#region Vars

	/// [kg] 
	[Tooltip ("Mass of object [kg]")] public float mass;
	/// Velocity this frame [m/s]
	[Tooltip ("Average velocity this frame [m/s]")] public Vector3 velocity;
	/// Net force vector for this frame (N) [kg*m/s^2]
	public Vector3 netForceVector;

	/// The forces acting on an object this frame
	private List<Vector3> forceVectorList = new List<Vector3> ();
	/// acceleration this frame [m/s^2]
	private Vector3 acceleration;


	#endregion

	void Start () {
		SetupThrustTrails ();
	}

	void FixedUpdate () {
		RenderTrails ();
		UpdatePosition ();
	}

	public void AddForce (Vector3 forceVector) {
		foreach(Vector3 force in forceVectorList) {
			if (force == forceVector) {
				return;
			}
		}

		forceVectorList.Add (forceVector);
	}

	void UpdatePosition () {
		netForceVector = Vector3.zero;

		foreach (Vector3 forceVector in forceVectorList) {
			netForceVector += forceVector;
		}
		forceVectorList.Clear ();

		acceleration = netForceVector / mass;
		velocity += acceleration * Time.fixedDeltaTime;
		transform.position += velocity * Time.fixedDeltaTime;
	}

	// Code for drawing thrust trails


	public bool showTrails = true;
	private LineRenderer lineRenderer;
	private int numberOfForces;

	void SetupThrustTrails () {
		lineRenderer = gameObject.AddComponent<LineRenderer> ();
		lineRenderer.material = new Material (Shader.Find ("Sprites/Default"));
		lineRenderer.startColor = Color.yellow;
		lineRenderer.endColor = Color.yellow;
		lineRenderer.startWidth = 0.2f;
		lineRenderer.endWidth = 0.2f;
		lineRenderer.useWorldSpace = false;
	}

	void RenderTrails () {
		if (showTrails) {
			lineRenderer.enabled = true;
			numberOfForces = forceVectorList.Count;
			lineRenderer.positionCount = numberOfForces * 2;
			int i = 0; 
			foreach (Vector3 forceVector in forceVectorList) {
				lineRenderer.SetPosition (i, Vector3.zero);
				lineRenderer.SetPosition (i + 1, -forceVector);
				i = i + 2;
			}
		} else {
			lineRenderer.enabled = false;
		}
	}

}
