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

public class GrenadeProjectile : BaseProjectile
{
    public static event EventHandler OnAnyGrenadeExploded;
    [SerializeField] private AnimationCurve arcYAnimationCurve;
    private float totalDistance;
    private Vector3 positionXZ;
    protected override void OnHitEffect()
    {
        float damageRadius = 4f;
        Collider[] colliderArray = Physics.OverlapSphere(targetPosition, damageRadius);
        SpendablePoints<HealthPoints> grenadeDamage = 30;

        foreach (var target in GetDamageableInBlastRange(targetPosition)) {
            target.Damage(grenadeDamage);
        }
        OnAnyGrenadeExploded?.Invoke(this, EventArgs.Empty);
        Instantiate(hitVFXPrefab, targetPosition + Vector3.up * 1f, Quaternion.identity);
    }
    
    public static IEnumerable<IDamageable> GetDamageableInBlastRange(Vector3 targetPosition) {
        float damageRadius = 4f;
        foreach (Collider collider in Physics.OverlapSphere(targetPosition, damageRadius)) {
            if (collider.TryGetComponent<IDamageable>(out IDamageable target)) {
                yield return target;
            }            
        }
    }
    protected override void SetDefaultMoveSpeed()
    { 
        moveSpeed = 15f;
    }

    protected override void SetupSpecific()
    {
        positionXZ = transform.position;
        positionXZ.y = 0;
        totalDistance = Vector3.Distance(positionXZ, targetPosition);
    }

    protected override float GetCurve()
    {
        positionXZ = transform.position;
        positionXZ.y = 0;
        float distance = Vector3.Distance(positionXZ, targetPosition);
        float distanceNormilized = 1 - (distance / totalDistance);
        float positionY = arcYAnimationCurve.Evaluate(distanceNormilized);
        float maxHeight = 3f;
        return positionY * maxHeight;
    }
}