using UnityEngine;
using Me.StefS.Utility;

public class Ship : MonoBehaviour
{
    public static float SCALE = 0.6f;
    public Vector3 location { get; set;}
    Vector3 oldLocation;
    public Vector3 flingVector { get; set; }
    public float currentVelocity = 0f;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update() {


        //this.transform.localRotation = Quaternion.LookRotation(this.oldLocation.VectorTo(this.location), new Vector3(0,1,0));
    }

    private static float calcAngle(Vector3 first, Vector3 second) {
        float angle =
            Mathf.Atan2(first.x * second.y - first.y * second.x,
                        first.x * second.x + first.y * second.y);
        angle = angle * (180 / Mathf.PI);

        angle = getSignum(first, second) * angle;
        return angle;
    }

    private static float getSignum(Vector3 vectorFrom, Vector3 vectorTo) {
        return 1;
    }

    internal void Initialize(Vector3 location, Vector3 flingVector) {
        this.location = location;
        this.flingVector = flingVector;
        this.oldLocation = this.location + Vector3.down;
      //  this.currentVelocity = flingVector.magnitude;
    }

    public void ApplyForce(Vector3 gravityPull, float deltaTime){
        Vector3 inertia = calculateInertia();
        this.oldLocation = this.location;
        Debug.Log("GP:" + gravityPull + " FV:" + flingVector + " IN" + inertia);
        Vector3 oneSecondVector = gravityPull + flingVector + inertia;
        this.location += oneSecondVector * deltaTime;
        currentVelocity = this.oldLocation.VectorTo(this.location).magnitude;
        flingVector = flingVector.normalized * Mathf.Lerp(flingVector.magnitude, 0, deltaTime);
        //this.transform.localRotation = Quaternion.LookRotation(flingVector, Vector3.up);

        //==========from the old update
        this.transform.localPosition = this.location * Constants.DISTANCE_SCALE;

        Vector3 first = this.oldLocation;
        Vector3 second = this.location;
        float angle = calcAngle(Vector3.up, first.VectorTo(second));

        //Vector3.up.AngleWith(this.location.VectorTo(this.oldLocation)) + 180f;
        this.transform.rotation = Quaternion.Euler(0, 0,  angle);

    }

    private Vector3 calculateInertia() {
        Debug.Log("cur velo" + currentVelocity);
        return this.oldLocation.VectorTo(this.location).normalized * currentVelocity * Constants.SHIP_MASS;
    }
}
