extends Node3D

const SPAWN_RANDOM_POSITION_RANGE = 10
const SPAWN_RANDOM_ANGLE_RANGE = PI/8

@export var delay : float = 5.
@export var duration : float = 10.
@export var spawn_rate : float = 30.
@export var horde_manager : AlienHordeManager

var current_frame : int = 0

var aliens : Array[Alien] = []
var clusters := []
var clusters_coords : Array[Vector2i] = []

var time_elapsed = 0.
var time_spawning = 0.

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
    if delay > 0:
        delay -= delta
    else:
        spawn_aliens(delta)

func spawn_aliens(delta):
    if time_elapsed < duration:
        time_elapsed += delta
        time_spawning += delta

        for i in range(roundi(spawn_rate * time_spawning)):
            time_spawning -= 1/spawn_rate
            spawn_alien()

func spawn_alien() -> Alien:
    var alien_position : Vector3 = Vector3(
        %SpawnPoint.global_position.x + randf_range(-SPAWN_RANDOM_POSITION_RANGE, SPAWN_RANDOM_POSITION_RANGE),
        0,
        %SpawnPoint.global_position.z + randf_range(-SPAWN_RANDOM_POSITION_RANGE, SPAWN_RANDOM_POSITION_RANGE)
    )

    var alien_rotation : float = rotation.y + randf_range(-SPAWN_RANDOM_ANGLE_RANGE, SPAWN_RANDOM_ANGLE_RANGE)

    return horde_manager.spawn_alien(alien_position, alien_rotation)
