using UnityEngine;
using System.Collections;

public class Enemy : MonoBehaviour
{
    public static Enemy instance;
    public Animator animator;
    public Transform player;
    public float attackRange = 5f;
    public LayerMask targetLayer;

    public Transform firePoint;
    public LineRenderer lr;
    public float distance = 10f;
    public int maxHealth = 3;
    public GameObject explosion;
    public Transform explosionPoint;
    public GameObject floatingTextPrefab;

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

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        lr.enabled = false;
    }

    // Update is called once per frame
    void Update()
    {
        if (maxHealth <= 0) {
            Die();
        }

        Collider2D collInfo = Physics2D.OverlapCircle(transform.position, attackRange, targetLayer);
        if (collInfo == true) {
            animator.SetBool("Attack", true);
        }
        else {
            animator.SetBool("Attack", false);
        }
    }

    public void Shoot() {
        StartCoroutine(ShootRaycast());
    }

    IEnumerator ShootRaycast() {
        lr.enabled = true;
        RaycastHit2D hitInfo = Physics2D.Raycast(firePoint.position, Vector2.left, distance, targetLayer);
        lr.SetPosition(0, firePoint.position);
        if (hitInfo) {
            
            if (hitInfo.transform.GetComponent<Player>() != null) {
                Player.instance.TakeDamage(1);
            }

            lr.SetPosition(1, hitInfo.point);
        }
        else {
            lr.SetPosition(1, firePoint.position + (-transform.right * distance));
        }
        yield return new WaitForSeconds(.12f);
        lr.enabled = false;
    }

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

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

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