extends Node2D

@onready var animated_sprite_2d: AnimatedSprite2D = $AnimatedSprite2D
@onready var death_timer: Timer = $DeathTimer
@onready var front: CollisionShape2D = $AnimatedSprite2D/Area2D/Front
@onready var back: CollisionShape2D = $AnimatedSprite2D/Area2D/Back
@onready var squish: AudioStreamPlayer2D = $Squish

signal player_died
const SPEED :int = 50
var direction :float = -1.0
var alive :bool = true


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	if !alive:
		return
		
	position.x += direction * SPEED * delta

func _on_area_2d_body_entered_for_death(body: Node2D) -> void:
	if body.name == "player":
		animated_sprite_2d.animation = "dying"
		squish.play()
		death_timer.start()
		front.set_deferred("disabled", true)
		back.set_deferred("disabled", true)
		alive = false
		position.x = position.x


func _on_body_entered(body: Node2D) -> void:
	if body.name == "player":
		emit_signal("player_died", body)
	else:
		direction *= -1
		animated_sprite_2d.flip_h = !animated_sprite_2d.flip_h


func _on_death_timer_timeout() -> void:
	queue_free()
