﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class Boss : MonoBehaviour {

    public int health;
    public int damage;
    private float timeBtwDamage = 1.5f;


    public Animator camAnim;
    public Slider healthBar;
    private Animator anim;
    public bool isDead;
    private bool facingRight = true; //Verifica se o player esta virado para a direita
    protected Transform target; // Alvo do inimigo

    private void Start()
    {
        anim = GetComponent<Animator>();
    }

    void Awake()
    {
        target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>(); // Define que o alvo é o player

    }

    private void Update()
    {
        if (Vector3.Distance(target.position, transform.position) < 20)
        {

            transform.position = Vector2.MoveTowards(transform.position, target.position, 0 * Time.deltaTime);
            if (target.position.x > transform.position.x && facingRight) //if the target is to the right of enemy and the enemy is not facing right
                Flip();
            if (target.position.x < transform.position.x && !facingRight)
                Flip();
        }

        if (health <= 12) {
            anim.SetTrigger("stageTwo");
        }

        if (health <= 0) {
            anim.SetTrigger("death");
        }

        // give the player some time to recover before taking more damage !
        if (timeBtwDamage > 0) {
            timeBtwDamage -= Time.deltaTime;
        }

        healthBar.value = health;
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        // deal the player damage ! 
        if (other.CompareTag("Ground") && isDead == false) {
            if (timeBtwDamage <= 0) {
                camAnim.SetTrigger("shake");
                //other.GetComponent<Player>().health -= damage;
            }
        }

        if (other.gameObject.tag == "Shot")
        {
            StartCoroutine(TookDanageCoRoutine());// Chama a co-rotina TookDamage
        }
    }

    protected void Flip()
    {
        facingRight = !facingRight; // Inverte o valor do facinRight

        Vector3 scale = transform.localScale; // vetor 3 será igual a escala atual do inimigo
        scale.x *= -1; //Pega o X da escala atual e multiplica por -1, para fazer a inverção
        transform.localScale = scale; //Atualiza a escala
    }

    IEnumerator TookDanageCoRoutine() //Co-rotina para trocar com do inimigo para quando ele tomar dano e não morrer
    {

        health--;
        if (health <= 0)
        {
            //Destroy(gameObject);
            yield return new WaitForSeconds(0.5f); //Espera o.1 segundos
            SceneManager.LoadScene("Fim");
        }
        
    }
}
