using UnityEngine;

public class Enemy1 : MonoBehaviour {

    [Header("Health")]
    [SerializeField] private int maxHealth = 3;
    [SerializeField] private GameObject floatingTextPrefab;
    [SerializeField] private Transform spawnPoint;

    [Header("Attack")]
    [SerializeField] private float attackRangeRadius = 5f;
    [SerializeField] private LayerMask whatIsPlayer;
    [SerializeField] private Transform player;
    [SerializeField] private GameObject arrowPrefab;
    [SerializeField] private Transform firePoint;
    [SerializeField] private float arrowSpeed = 10f;

    private bool facingLeft;
    private Animator animator;
    private BoxCollider2D boxCollider2D;
    private Rigidbody2D rb;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start() {
        facingLeft = true;
        rb = this.gameObject.GetComponent<Rigidbody2D>();
        animator = this.gameObject.GetComponent<Animator>();
        boxCollider2D = this.gameObject.GetComponent<BoxCollider2D>();
    }

    // Update is called once per frame
    void Update() {

        Collider2D collInfo = Physics2D.OverlapCircle(transform.position, attackRangeRadius, whatIsPlayer);

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

    void Flip() {

        if (transform.position.x < player.position.x && facingLeft) {
            transform.eulerAngles = new Vector3(0f, -180f, 0f);
            facingLeft = false;
        }
        else if (transform.position.x > player.position.x && !facingLeft) {
            transform.eulerAngles = new Vector3(0f, 0f, 0f);
            facingLeft = true;
        }
    }

    public void SpawnArrow() {
        GameObject tempArrowPrefab = Instantiate(arrowPrefab, firePoint.position, firePoint.rotation);
        tempArrowPrefab.gameObject.GetComponent<Rigidbody2D>().linearVelocity = -firePoint.right * arrowSpeed;
    }

    public void TakeDamage(int damageAmount) {

        if (maxHealth <= 1) {
            Die();
            return;
        }
        maxHealth -= damageAmount;

        CameraShake.instance.Shake(.2f, 4f);

        animator.SetTrigger("Hurt");
        GameObject tempFloatingTextPrefab = Instantiate(floatingTextPrefab, spawnPoint.position, Quaternion.identity);
        Destroy(tempFloatingTextPrefab, 1f);
    }

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

    void Die() {
        Debug.Log(this.gameObject.name + " Died!");
        animator.SetTrigger("Death");
        rb.gravityScale = 0f;
        boxCollider2D.enabled = false;
        Destroy(this.gameObject, 5f);
    }
}
