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

public class Mine : MetalObject
{
    [SerializeField] float ExplosionRadius = 4f;
    [SerializeField] float ExplosionDelay = 2f;
    [SerializeField] float Damage = 120f;
    [SerializeField] AnimationCurve DamageFalloff;
    [SerializeField] LayerMask PlayerMask;
    [SerializeField] AudioClip SFXActivate;
    [SerializeField] AudioClip SFXExplode;
    [SerializeField] GameObject VFXExplosion;
    [SerializeField] Animator Animator;

    private void OnCollisionEnter(Collision collision)
    {
        if (PlayerMask != (PlayerMask | (1 << collision.gameObject.layer))) return;

        StartCoroutine(Explode());
    }

    private IEnumerator Explode()
    {
        if(SFXActivate != null)
            AudioSource.PlayClipAtPoint(SFXActivate, transform.position);
        Animator?.SetTrigger("Pickup");

        yield return new WaitForSeconds(ExplosionDelay);
        
        Collider[] hits = Physics.OverlapSphere(transform.position, ExplosionRadius);
        if (hits != null && hits.Length > 0)
        {
            DealDamageToAll(hits);
        }

        if(SFXExplode != null)
            AudioSource.PlayClipAtPoint(SFXExplode, transform.position);
        if (VFXExplosion != null)
            Instantiate(VFXExplosion, transform.position, Quaternion.identity);

        Destroy(gameObject);
    }

    private void DealDamageToAll(Collider[] hits)
    {
        for (int i = 0; i < hits.Length; i++)
        {
            Health h = hits[i].GetComponent<Health>();
            if (h != null)
            {
                float distance = Vector3.Distance(transform.position, hits[i].transform.position);
                float damage = Damage * DamageFalloff.Evaluate(1 - (distance / ExplosionRadius));
                h.Hit(damage);
            }
        }
    }

    public void OnAnimationEnd()
    {
    }
}
