class_name LevelArea
extends Area3D

@export var level_loader: LevelLoader
@export var loaded_if_spawnpoint: Array[PlayerSpawnPoint] = []
@export var keep_loaded_duration: float = 3.0


func _enter_tree() -> void:
	for spawnpoint: PlayerSpawnPoint in loaded_if_spawnpoint:
		if GameGlobals.spawn_id == spawnpoint.spawn_id:
			var was_threaded: bool = level_loader.load_threaded
			level_loader.load_threaded = false
			load_level()
			level_loader.load_threaded = was_threaded
			return


func _ready() -> void:
	await get_tree().process_frame
	await get_tree().process_frame

	body_entered.connect(load_level.unbind(1))
	body_exited.connect(unload_level.unbind(1))


func load_level() -> void:
	assert(is_instance_valid(level_loader), "Level loader needs to be set.")
	level_loader.load_level()


func unload_level() -> void:
	assert(is_instance_valid(level_loader), "Level loader needs to be set.")

	if keep_loaded_duration > 0.0:
		var duration: float = keep_loaded_duration

		while duration > 0.0:
			if has_overlapping_bodies():
				return

			duration -= get_process_delta_time() * float(not get_tree().paused)
			await get_tree().process_frame

			if not is_inside_tree() or not is_instance_valid(get_tree()):
				return

	level_loader.unload_level()
