extends Node3D

signal matador_killed

const MATADOR := preload("res://Matador.tscn")
const RESPAWN_COOLDOWN := 8.0

var _respawn_cooldown: float = 0.0


func _ready() -> void:
	add_to_group(&"matador_spawn")
	_spawn.call_deferred()


func _process(delta: float) -> void:
	_respawn_cooldown = maxf(0.0, _respawn_cooldown - delta)


func _unhandled_input(event: InputEvent) -> void:
	if event is InputEventKey and event.pressed and not event.echo:
		if event.physical_keycode == KEY_R and _respawn_cooldown <= 0.0:
			_respawn_cooldown = RESPAWN_COOLDOWN
			reset_spawn()


func _spawn() -> void:
	var count: int = int(DP.f("mat_spawn_count"))
	for i: int in count:
		_spawn_one()


func _spawn_one() -> void:
	var m: Node3D = MATADOR.instantiate()
	m.position = Vector3(0.0, 1.0, 0.0)
	get_parent().add_child(m)
	m.killed.connect(_on_matador_killed)


func _on_matador_killed() -> void:
	matador_killed.emit()
	_spawn_one.call_deferred()


func reset_spawn() -> void:
	for m: Node in get_tree().get_nodes_in_group(&"matador"):
		m.queue_free()
	await get_tree().process_frame
	_spawn()
