class_name InteractiveLoader
extends Node

@export var auto_free: bool = false

var load_progress: Array = []


func load_threaded(path: String) -> Resource:
	if not is_inside_tree():
		SPrint.print_msg("[Interactive Loader] needs to be added to the scene tree.", -1.0, SPrint.WARNING)
		return null

	if not ResourceLoader.exists(path):
		SPrint.print_msg("[Interactive Loader] the given path (%s) doesn't exist." % path, -1.0, SPrint.WARNING)
		return null

	ResourceLoader.load_threaded_request(path, "", false, ResourceLoader.CACHE_MODE_REUSE)

	while ResourceLoader.load_threaded_get_status(path) != ResourceLoader.THREAD_LOAD_LOADED:
		match ResourceLoader.load_threaded_get_status(path, load_progress):
			ResourceLoader.THREAD_LOAD_FAILED || ResourceLoader.THREAD_LOAD_INVALID_RESOURCE:
				SPrint.print_msg("[Interactive Loader] load failed.", -1.0, SPrint.WARNING)
				return null

		if is_inside_tree():
			await get_tree().process_frame
		else:
			SPrint.print_msg("[Interactive Loader] is no longer in the scene tree. We can't wait for a process frame anymore, resulting in a freeze.", -1.0, SPrint.WARNING)

	if auto_free:
		queue_free()

	return ResourceLoader.load_threaded_get(path)
