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

public class EnemyController : MonoBehaviour
{
    public float alpha = -1f;

    public float speed = 3f;

    public float semiMajor = 3f;
    public float semiMinor = 1f;
    public float percentPower = 1f;
    private float magnitude = 3f;

    public float X;
    public float Y;

    public float tiltAngle = 45f;
    public bool UpdateRotation = true;

    public static readonly float RotationAlphaDelta = 5f;

    public static readonly float EndAlpha = 330f;

    // Start is called before the first frame update
    void Start()
    {
        this.X = this.transform.position.x;
        this.Y = this.transform.position.y;
        this.tiltAngle = Random.Range(0, 360f);
        this.speed = Random.Range(.5f, 1.5f);
        this.semiMajor = Random.Range(1f, 3f);
    }

    private Vector3 GetFiringAngle()
    {
        Controller c = this.GetComponent<Controller>();
        if (c)
        {
            float xaxis = c.h_axis;
            float yaxis = c.v_axis;
            Vector3 v = new Vector3(xaxis, yaxis, 0);
            return v.normalized;
        }
        else { return Vector3.zero; }
    }

    private Vector3 GetFacingVector(float alpha)
    {
        return CalcPosition(alpha + RotationAlphaDelta) - CalcPosition(alpha);
    }

    private Vector2 CalcPosition(float alpha)
    {
        float multiplier = percentPower * magnitude;
        float major = multiplier * semiMajor;
        float minor = multiplier * semiMinor;
        Vector2 pos = new Vector2(X + (major * MCos(alpha) * MCos(tiltAngle)) - (minor * MSin(alpha) * MSin(tiltAngle)),
                                         Y + (major * MCos(alpha) * MSin(tiltAngle)) + (minor * MSin(alpha) * MCos(tiltAngle)))
                                         * -1                                       // Invert direction.
                                         + (AngleToVector(tiltAngle) * major);  // Rotate 90 degs.
        return pos;
    }

    void Update()
    {
        Vector3 newPos = CalcPosition(alpha);
        transform.position = new Vector3(newPos.x, newPos.y, transform.position.z);
        if (this.UpdateRotation)
        {
            transform.rotation = Quaternion.Euler(new Vector3(0, 0, VectorToAngle(GetFacingVector(alpha)) + 90));
        }
        alpha -= speed;
    }

    float MCos(float value)
    {
        return Mathf.Cos(Mathf.Deg2Rad * value);
    }

    float MSin(float value)
    {
        return Mathf.Sin(Mathf.Deg2Rad * value);
    }

    Vector2 AngleToVector(float angle)
    {
        return new Vector2(MCos(angle), MSin(angle));
    }

    float VectorToAngle(Vector2 vec)
    {
        return Mathf.Atan2(vec.y, vec.x) * 180f / Mathf.PI;
    }
}
