extends Node

class_name SceneSelectorUtility

# Cache of scene paths
var _scene_paths_cache = {}

# Cache of loaded scenes (only populated if preload_scenes is true)
var _loaded_scenes_cache = {}

# Initialize the cache for a specific folder
func initialize_cache(folder_path: String, preload_scenes: bool = false):
	if _scene_paths_cache.has(folder_path):
		return # Already cached
		
	var dir = DirAccess.open(folder_path)
	if not dir:
			push_error("Error: Could not open directory: " + folder_path)
			return
		
	var scene_files = []

	# List all scene files
	dir.list_dir_begin()
	var file_name = dir.get_next()

	while file_name != "":
			if file_name.ends_with(".tscn"):
					scene_files.append(folder_path + "/" + file_name)
			file_name = dir.get_next()

	#Log.pr("Found %d scene files in %s" % [scene_files.size(), folder_path])
	# Store in cache
	_scene_paths_cache[folder_path] = scene_files

	# Optionally preload all scenes
	if preload_scenes and scene_files.size() > 0:
			_loaded_scenes_cache[folder_path] = []
			for scene_path in scene_files:
				#Log.pr("Preloading scene: " + scene_path)
				# Load the scene and store it in the cache
				#var loaded_scene = preload(scene_path)
				_loaded_scenes_cache[folder_path].append(load(scene_path))
			

# Get a random scene from a folder (using caches)
func get_random_scene(folder_path: String):
	# Make sure the cache is initialized
	if not _scene_paths_cache.has(folder_path):
		#Log.pr("Initializing cache for folder: " + folder_path)
		initialize_cache(folder_path, true)
	
	var scene_paths = _scene_paths_cache[folder_path]
	if scene_paths.size() == 0:
		push_error("No scene files found in directory: " + folder_path)
		return null
	
	# Get random index
	var random_index = RNG.randi_range(0, scene_paths.size() - 1)
	
	# Return from loaded scenes cache if available
	if _loaded_scenes_cache.has(folder_path):
		#Log.pr("Returning preloaded scene from cache")
		return _loaded_scenes_cache[folder_path][random_index]
	
	# Otherwise load the scene
	var scene = load(scene_paths[random_index])
	#Log.pr(scene)
	return scene
