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

public class ArcProjectile : TargetedProjectile
{
    [Header("Arc Projectile")]
    [SerializeField, Range(0, 90)]
    private float _angle = 45.0f;

    protected override void ApplyMovement()
    {
        if (Target != null)
        {
            EndPos = Target.Position;
        }

        // position:
        // k(ax^2 + x)
        // k: angle comme ratio opposé / adjacent
        // a: -1 / distance
        // x: position x sur l'arc
        // y: position y sur l'arc
        float distance = (EndPos.x - StartPos.x);
        float k = Mathf.Sign(distance) * Mathf.Tan(_angle * Mathf.Deg2Rad);
        float a = -1.0f / distance;
        float x = (transform.position.x - StartPos.x) + Speed * Time.deltaTime;
        float y = k * (a * x * x + x);
        Vector2 newPos = new Vector2(StartPos.x + x, StartPos.y + y);
        transform.position = newPos;

        // rotation:
        // k(2ax + 1)
        // (c'est la dérivée de la position)
        float dDx = k * (2 * a * x + 1);
        float rotationAngle = Mathf.Atan(dDx) * Mathf.Rad2Deg;
        transform.eulerAngles = new Vector3(0, 0, rotationAngle);

        if (y < 0)
        {
            Destroy(gameObject);
        }
    }

    protected override void HandleCollision(Collider2D other)
    {
        if (Target == null) return;
        if (other.gameObject != Target.gameObject) return;

        if (other.TryGetComponent(out Entity target))
        {
            ApplyEffects(target);
            target.Hit(Damage);
            if (target.Hp <= 0)
            {
                target.Death();
            }
            Destroy(gameObject);
        }
    }

    public float Angle { get => _angle; set => _angle = value; }
}
