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

public class Snake : MonoBehaviour
{
    public GameObject bulletPrefab; //Instancia o prefab bullet
    public Transform shotSpawner; //Spawner do tiro
    protected bool facingRight = true;
    protected float targetDistance;
    public float attackDistance; //Distancia do ataque inimigo
    private float nextFire;
    public float fireRate;
    public Animator animator; //Animator será animator
    protected Transform target; // Alvo do inimigo
    public float speed;
    public int health = 3;
    protected SpriteRenderer sprite; // Define o spriterenderer como sprite
    public AudioSource tiro;

    // Start is called before the first frame update
    void Awake()
    {
        target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>(); // Define que o alvo é o player
        
    }

    void Start()
    {
        sprite = GetComponent<SpriteRenderer>(); //Pega o comonente spriterenderer e atribui para sprite
        tiro = GetComponent<AudioSource>();
    }

    // Update is called once per frame
    void Update()
    {
        targetDistance = transform.position.x - target.position.x; //  Quado a distancia for  menor que a distancia do ataque o objeto ou começa a seguir o payer ou atacar

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

            transform.position = Vector2.MoveTowards(transform.position, target.position, speed * 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 (Mathf.Abs(targetDistance) < attackDistance && Time.time > nextFire)
        {
            animator.SetBool("perto", true);
            nextFire = Time.time + fireRate;
            //Shooting();
        }
        else
        {
            animator.SetBool("perto", false);
        }
    }


    public void Shooting()
    {
        GameObject tempBullet = Instantiate(bulletPrefab, shotSpawner.position, shotSpawner.rotation);
        tiro.Play();
        if (!facingRight)
        {
            tempBullet.transform.eulerAngles = new Vector3(0, 0, 180);
        }
    }    

    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
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "Shot")
        {
            health--;
            if (health <= 0)
            {
                Destroy(gameObject);
            }
            else
            {
                StartCoroutine(TookDanageCoRoutine());// Chama a co-rotina TookDamage
            }
        }
    }

    IEnumerator TookDanageCoRoutine() //Co-rotina para trocar com do inimigo para quando ele tomar dano e não morrer
    {
        sprite.color = Color.red; //Define cor do sprite para vermellho
        yield return new WaitForSeconds(0.1f); //Espera o.1 segundos
        sprite.color = Color.white; // Volta com do sprite para branco (cor normal)

    }
}



