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

public class CBoss : MonoBehaviour
{
    public Animator _anim;
    public BoxCollider2D _hitCollider;

    public float distanciaParaActivarse;
    public GameObject player;
    float distanciaPlayerX;
    bool activarse = false;

    public float _timeBtwAtacks;
    public float _randomTimer;

    public float _currentTimer = 0;

    bool atacar = true;
    bool activarMuerte = true;

    public BoxCollider2D collAtaque;
    public AtaqueEnemigo ataqueScript;
    public UnidadEnemigo unidad;

    public Coroutine _activeRoutine;

    private void Awake()
    {
        _anim = GetComponent<Animator>();
    }

    private void Update()
    {
        Debug.Log(_currentTimer);

        distanciaPlayerX = Mathf.Abs(player.transform.position.x - transform.position.x);

        if (activarse == true)
        {
            _currentTimer += Time.deltaTime;

            if (unidad.vivo == true)
            {
                if (distanciaPlayerX <= 7)
                {
                    if (atacar == true)
                    {
                        Debug.Log("Log");

                        if (_currentTimer >= _timeBtwAtacks + Random.Range(-_randomTimer, _randomTimer))
                        {
                            Atack();
                        }
                    }
                }

                if (unidad.golpeRecibido == true)
                {
                    StartCoroutine(DañoRecibido(0.5f));

                    unidad.golpeRecibido = false;
                }

            }

            else
            {

                if (activarMuerte == true)
                {
                    Muerto();
                    activarMuerte = false;
                }

            }
        }
        else
        {
            if (distanciaPlayerX <= distanciaParaActivarse)
            {
                activarse = true;
            }
        }
    }

    public void Atack()
    {
        _activeRoutine = StartCoroutine(AtackRoutine());
        atacar = false;
    }

    public IEnumerator AtackRoutine()
    {
        _anim.SetTrigger("Hit");

        yield return new WaitForSeconds(0.4f);
        ataqueScript.atacando = true;
        yield return new WaitForSeconds(0.05f);
        ataqueScript.atacando = false;

        _currentTimer = 0;
        atacar = true;

        yield return null;
    }

    IEnumerator DañoRecibido(float time)
    {
        _anim.SetTrigger("Hitted");
        yield return new WaitForSeconds(time);
    }
    void Muerto()
    {
        _anim.SetBool("Muerto", true);

        collAtaque.enabled = false;
        print("muerto");
        Destroy(gameObject, 2f);
        activarMuerte = false;
    }
}
