using System.Collections;
using UnityEngine;

public class EnemyMovment : MonoBehaviour
{
    public Transform pointA;
    public Transform pointB;
    public float speed = 2f;

    [SerializeField] private int EnemyHealth = 5;

    public int Health => EnemyHealth;

    public delegate void EnemyDefeatedEventHandler(EnemyMovment enemy);
    public static event EnemyDefeatedEventHandler EnemyDefeated;

    private void Start()
    {
        StartCoroutine(MoveBetweenPoints());
    }

    private void Update()
    {
        if (EnemyHealth <= 0)
        {
            OnEnemyDefeated();
        }
    }

    private void OnEnemyDefeated()
    {
       
        EnemyDefeated?.Invoke(this);
        
        Destroy(gameObject);
    }

    private IEnumerator MoveBetweenPoints()
    {
        while (true)
        {
            while (Vector3.Distance(transform.position, pointB.position) > 1f)
            {
                transform.Translate((pointB.position - transform.position).normalized * speed * Time.deltaTime);
                yield return null;
            }

            yield return new WaitForSeconds(1.0f);

            while (Vector3.Distance(transform.position, pointA.position) > 1f)
            {
                transform.Translate((pointA.position - transform.position).normalized * speed * Time.deltaTime);
                yield return null;
            }

            yield return new WaitForSeconds(1.0f);
        }
    }

    [ContextMenu("TakeDmg")]
    public void TakeDamage()
    {
        EnemyHealth--;
    }
}
