using UnityEngine;

public class GravityTower : Tower
{
    [SerializeField, Range(0.1f, 10f)]
    private float radius = 1f;

    [SerializeField]
    private Transform orb;

    [SerializeField]
    private LayerMask affectedBodies;

    [SerializeField]
    private AnimationCurve distToAcceleration;

    [SerializeField]
    private string audioName;
    private AudioSource audioSc;

    protected override void Awake()
    {
        base.Awake();
    }

    protected override void Start()
    {
        base.Start();

        if (!string.IsNullOrEmpty(audioName))
        {
            audioSc = AudioManager.PlaySound(audioName, transform.position, false, true, true);
        }
    }

    protected override void FixedUpdate()
    {
        if (GameManager.Instance.CurrentNumEnemies == 0) return;

        Collider[] projectilesInRadius = Physics.OverlapSphere(orb.position, radius, affectedBodies);
        foreach (var projectile in projectilesInRadius)
        {
            Rigidbody projectileBody = projectile.GetComponent<Rigidbody>();
            Vector3 projToOrb = orb.position - projectile.transform.position;
            float dist = projToOrb.magnitude;
            projectileBody.AddForce(projToOrb.normalized * distToAcceleration.Evaluate(dist));
        }
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();

        if (audioSc != null)
            audioSc.Stop();
    }

    protected override void Update()
    {
        base.Update();
    }
}