using UnityEngine;

public class Enemy2 : MonoBehaviour
{
    public static Enemy2 instance;
    public int maxHealth = 2;
    public Animator animator;
    public Transform player;
    public float attackRange = 4f;
    public LayerMask targetLayer;

    public Transform attackPoint;
    public float attackRadius = 1f;
    public LayerMask DamageLayer;
    public GameObject floatingTextPrefab;
    public GameObject explosionEffect;
    public Transform spawnEffectPoint;

    private void Start()
    {
        if (instance == null) {
            instance = this;
        }
        else {
            Destroy(this);
        }
    }

    void Update()
    {
        if (maxHealth <= 0) {
            Die();
        }

        Collider2D collInfo = Physics2D.OverlapCircle(transform.position, attackRange, targetLayer);

        if (collInfo) {
            animator.SetBool("Attack", true);
        }
        else {
            animator.SetBool("Attack", false);
        }
    }

    public void Attack() {
        Collider2D collInfo = Physics2D.OverlapCircle(attackPoint.position, attackRadius, DamageLayer);
        if (collInfo) {
            if (collInfo.gameObject.GetComponent<Player>() != null) {
                Player.instance.TakeDamage(1);
            }
        }
    }

    public void TakeDamage() {
        if (maxHealth <= 0) {
            return;
        }
        maxHealth -= 1;
        CameraShake.instance.Shake();
        Instantiate(floatingTextPrefab, transform.position, Quaternion.identity);
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, attackRange);

        if (attackPoint == null) {
            return;
        }
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(attackPoint.position, attackRadius);
    }

    void Die() {
        Debug.Log(this.transform.name + " Died!");
        CameraShake.instance.Shake();
        FindAnyObjectByType<SoundManager>().PlayExplosionSound();
        GameObject tempExplosionEffect = Instantiate(explosionEffect, spawnEffectPoint.position, Quaternion.identity);
        Destroy(tempExplosionEffect, .9f);
        Destroy(this.gameObject);
    }
}
