extends Path3D
class_name Spawner

@export var waves : Array[Wave]
var current_wave : Wave
var current_troop : Troop

var enemies_to_spawn : int = 0
var can_spawn : bool = false
var wave_on_going : bool = false

func spawn_next_wave() -> void:

	current_wave = waves.pop_front()
	$SpawnTimer.start(current_wave.wait_time_before_next_wave)



func _process(delta: float) -> void:
	spawn_manager()


func spawn() -> void:
		$SpawnTimer.start()
		var tempEnemy = current_troop.enemy.instantiate()
		add_child(tempEnemy)
		
		enemies_to_spawn -= 1
		GameManager.enemies_alive += 1
		
		can_spawn = false


func spawn_manager() -> void:
	if !can_spawn:
		return
	
	if !current_wave.troops.is_empty() and enemies_to_spawn == 0:
		current_troop = current_wave.troops.pop_front()
		enemies_to_spawn = current_troop.number_to_spawn
	
	if enemies_to_spawn > 0:
		spawn()
	
	if GameManager.enemies_alive > 0:
		wave_on_going = true
	else:
		wave_on_going = false
		spawn_next_wave()


func _on_spawn_timer_timeout() -> void:
	can_spawn = true
	$SpawnTimer.wait_time = 1.0
