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

public class MeleeAlly : BaseAlly, TargetWithLifeThatNotifies.IDeathNotifiable
{
    [SerializeField] float Damage = 1;
    [SerializeReference] float AttackCadence = 1;
    [SerializeField] GameObject particleDust;

    float TimeToNextAttack = 0;
    List<TargetBase> CurrentTargets;
    Animator[] SpikesAnim;
    Animator anim;
    bool IsAttacking = false;

    private void Awake()
    {
        CurrentTargets = new List<TargetBase>();
        SpikesAnim = GetComponentsInChildren<Animator>();
        anim = GetComponentInParent<Animator>();
    }

    void Update()
    {
        if(CurrentTargets.Count > 0)
        {
            TimeToNextAttack -= Time.deltaTime;
            TimeToNextAttack = TimeToNextAttack > 0f ? TimeToNextAttack : 0f;

            if (TimeToNextAttack <= 0)
            {
                TimeToNextAttack = 1f / AttackCadence;

                AttackEnemiesInside();

                Debug.Log("Ataco a sombi");
            }
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Enemy"))
        {
            TargetBase target = collision.GetComponent<TargetBase>();
            if(target)
            {
                CurrentTargets.Add(target);
            }
        }
    }

    private void AttackEnemiesInside()
    {
        Instantiate(particleDust, transform.position, transform.rotation);
        FMODUnity.RuntimeManager.PlayOneShot("event:/Foley/MeleePlant");
        foreach (Animator animator in SpikesAnim)
        {
            animator.SetTrigger("SpikesUp"); 
        }
        for(int i = 0; i < CurrentTargets.Count; i++)
        {
            CurrentTargets[i].NotifySwing(Damage);
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.CompareTag("Enemy"))
        {
            TargetBase target = collision.GetComponent<TargetBase>();
            if (target && CurrentTargets.Contains(target))
            {
                CurrentTargets.Remove(target);
            }
        }
    }

    void TargetWithLifeThatNotifies.IDeathNotifiable.NotifyDeath()
    {
        if (!Dead)
        {
            Dead = true;
            GetComponentInParent<CircleCollider2D>().enabled = false;
            Invoke("Death", 1f);
            anim.SetTrigger("Death");
        }
    }
}
