extends Node2D

@onready var animated_sprite_2d: AnimatedSprite2D = $AnimatedSprite2D
@onready var wait_timer: Timer = $WaitTimer
@onready var collision_shape_2d: CollisionShape2D = $Area2D/CollisionShape2D
@onready var death_collision_box: CollisionShape2D = $DeathBox/DeathCollisionBox
@onready var hit_box_wait: Timer = $HitBoxWait
@onready var animation_timer: Timer = $AnimationTimer
@onready var death_sound: AudioStreamPlayer2D = $DeathSound

var direction :float = 1.0
const SPEED = 150

signal player_died
var wait :bool = false
var alive :bool = true

func _process(delta: float) -> void:
	if !alive:
		return
	if !wait:
		position.x += direction * SPEED * delta

func _on_area_2d_body_entered(body: Node2D) -> void:
	if !alive:
		return
	if body.name == "player":
		emit_signal("player_died", body)
	else:
		wait = true
		_death_box_enabled()
		animated_sprite_2d.animation = "idle"
		animated_sprite_2d.flip_h = !animated_sprite_2d.flip_h
		wait_timer.start()

func _on_wait_timer_timeout() -> void:
	if !alive:
		return
	animated_sprite_2d.animation = "run"
	hit_box_wait.start()
	wait = false
	direction *= -1

func _death_box_enabled() -> void:
	collision_shape_2d.set_deferred("disabled", true)
	death_collision_box.set_deferred("disabled", false)
	
func _death_box_disabled() -> void:
	collision_shape_2d.set_deferred("disabled", false)
	death_collision_box.set_deferred("disabled", true)

func _on_death_box_body_entered(body: Node2D) -> void:
	if body.name == "player":
		alive = false
		animated_sprite_2d.animation = "die"
		death_sound.play()
		animation_timer.start()

func _on_hit_box_wait_timeout() -> void:
	_death_box_disabled()


func _on_animation_timer_timeout() -> void:
	queue_free()
