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

public class FloorAlly : BaseAlly, TargetWithLifeThatNotifies.IDeathNotifiable
{
    [SerializeField] float Damage = 1;
    [SerializeReference] float AttackCadence = 2;
    [SerializeReference] float VelocityMultiplier = 0.5f;

    Animator anim;

    float TimeToNextAttack = 0;
    int EnemyCount = 0;

    private void Awake()
    {
        anim = GetComponentInParent<Animator>();
    }

    void Start()
    {
        
    }

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

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Enemy"))
        {
            EnemyCount++;
            NavMeshAgent agent = collision.GetComponent<NavMeshAgent>();
            if (agent)
            {
                agent.speed *= VelocityMultiplier;
            }
        }
    }

    private void OnTriggerStay2D(Collider2D collision)
    {
        TargetBase target = collision.GetComponent<TargetBase>();
        if (target && collision.CompareTag("Enemy"))
        {
            if(TimeToNextAttack <= 0)
            {
                TimeToNextAttack = 1f / AttackCadence;
                target.NotifySwing(Damage);
            }
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.CompareTag("Enemy"))
        {
            EnemyCount--;
            NavMeshAgent agent = collision.GetComponentInParent<NavMeshAgent>();
            if (agent)
            {
                agent.speed /= VelocityMultiplier;
            }
        }
    }

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

}
