class_name 	EnemyBase
extends CharacterBody2D

@onready var animated_sprite_2d: AnimatedSprite2D = $AnimatedSprite2D
@export var drop_table: Array[DropTable]

var is_dying = false
var is_hurt = false
var hits_remaining = 1
var speed
var witch
var player
var death_sound = preload("res://assets/music&sfx/sfx/hit2.wav")
var last_direction := Vector2.DOWN
signal died

func _ready() -> void:
	add_to_group("enemies")
	died.connect(get_node("/root/Game/DropManager").on_enemy_died)
	witch = get_node("/root/Game/Witch")
	player = get_node("/root/Game/Player")
	animated_sprite_2d.sprite_frames = animated_sprite_2d.sprite_frames.duplicate()

func die():
	is_dying = true
	collision_layer = 0
	var death_anim: String
	if abs(last_direction.x) >= abs(last_direction.y):
		death_anim = "death_left" if last_direction.x < 0 else "death_right"
	else:
		death_anim = "death_up" if last_direction.y < 0 else "death_down"
	animated_sprite_2d.sprite_frames.set_animation_loop(death_anim, false)
	animated_sprite_2d.play(death_anim)
	var player = AudioStreamPlayer.new()
	add_child(player)
	player.stream = death_sound
	player.bus = "SFX"
	player.play()
	died.emit(self)
	await animated_sprite_2d.animation_finished
	queue_free()

func hit() -> void:
	if is_dying or is_hurt:
		return
	hits_remaining -= 1
	if hits_remaining <= 0:
		die()
	else:
		_play_hurt()

func _play_hurt() -> void:
	is_hurt = true
	var hurt_anim: String
	if abs(last_direction.x) >= abs(last_direction.y):
		hurt_anim = "hurt_left" if last_direction.x < 0 else "hurt_right"
	else:
		hurt_anim = "hurt_up" if last_direction.y < 0 else "hurt_down"
	animated_sprite_2d.sprite_frames.set_animation_loop(hurt_anim, false)
	animated_sprite_2d.play(hurt_anim)
	await animated_sprite_2d.animation_finished
	is_hurt = false

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	pass

func _chase_witch() -> void:
	var direction = Vector2(witch.global_position - global_position)
	if direction != Vector2.ZERO:
		last_direction = direction
	velocity = direction * speed
	velocity = direction * speed

	if direction == Vector2.ZERO:
		animated_sprite_2d.play("idle")
	elif abs(direction.x) >= abs(direction.y):
		if direction.x < 0:
			animated_sprite_2d.play("walk_left")
		else:
			animated_sprite_2d.play("walk_right")
	else:
		if direction.y < 0:
			animated_sprite_2d.play("walk_up")
		else:
			animated_sprite_2d.play("walk_down")
	move_and_slide()
