using UnityEngine;

/*
--------------------------------------
    Project: Programing assessment
    Standard: 91906 (AS3.7) v.1
    School: Tauranga Boys' College
    Author: Rauputu Noah Phizacklea
    Date: August 2024
    Unity: 2021.3.18f
---------------------------------------
*/

public class EnemyHealth : MonoBehaviour
{
    [SerializeField] private HitFlash flashEffect;    // Reference to the hit flash effect
    public Animator animator;                        // Animator for the enemy
    public int maxHealth = 100;                      // Maximum health of the enemy
    private int currentHealth;                       // Current health of the enemy
    public HealthBar healthBar;                      // Reference to the health bar
    public Vector3 respawnPosition;                  // Position where the enemy respawns
    AudioManager audioManager;                      // Reference to the AudioManager

    void Awake() 
    {
        // Find and assign the AudioManager component from an object tagged "Audio"
        audioManager = GameObject.FindGameObjectWithTag("Audio").GetComponent<AudioManager>();
    }

    void Start()
    {
        currentHealth = maxHealth; // Initialize current health to maximum health
        respawnPosition = transform.position; // Set respawn position to current position
    }

    public void TakeDamage(int damage)
    {
        // Subtract damage from current health and update the health bar
        currentHealth -= damage;
        healthBar.SetHealth(currentHealth);

        // Play hit flash effect
        flashEffect.Flash();

        // Check if health is zero or below
        if (currentHealth <= 0)
        {
            // Play death sound effect and handle death
            audioManager.PlaySFX(audioManager.slimeDeathSFX);
            Die();
        }
    }

    void Die()
    {
        // Deactivate the enemy GameObject
        gameObject.SetActive(false);
    }

    public void Respawn()
    {
        // Reset health, position, and re-enable the enemy GameObject
        currentHealth = maxHealth; 
        transform.position = respawnPosition; 
        gameObject.SetActive(true); 
        
        // Update the health bar if it's assigned
        if (healthBar != null)
        {
            healthBar.SetHealth(currentHealth); 
        }
    }
}