extends Node

signal finished_compilation

const EXCLUDED_DIRECTORIES: Array[String] = [
	"res://addons",
	"res://.godot",
]

#const SIMUTANEOUS_SCENES: int = 5

@onready var progress_bar: ProgressBar = %ProgressBar
@onready var canvas_layer: CanvasLayer = $CanvasLayer


func precompile_shaders() -> void:
	var files: PackedStringArray = find_scene_file_paths("res://")
	var index: int = 0
	
	while index < files.size():
		#print("Compilation Progress: ", index, "/", files.size() - 1)
		
		var file: String = files[index]
		index += 1
		
		if scene_file_path == file or get_tree().current_scene.scene_file_path == file:
			continue
		
		await compile_scene(file)
		
		progress_bar.value = index / float(files.size())
	
	finished_compilation.emit()


func compile_scene(scene_path: String) -> void:
	var scene: PackedScene = load(scene_path)
	
	if not scene.can_instantiate():
		return
	
	var node: Node = scene.instantiate()
	
	node.set_script(null)
	
	for child: Node in Utils.get_all_children(node):
		child.set_script(null)
		#child.set_process(false)
		#child.set_process_internal(false)
		#child.set_physics_process_internal(false)
	
	add_child(node)
	await get_tree().create_timer(0.2, false).timeout
	node.queue_free()


func find_scene_file_paths(path: String, find_recursive: bool = true) -> PackedStringArray:
	var files: PackedStringArray = []
	
	for file: String in DirAccess.get_files_at(path):
		if file.get_extension().contains("scn"):
			#print("Path: '%s' Filename: '%s'" %[path, file])
			files.append(str(path, "/" if not path.ends_with("/") else "", file))
	
	if find_recursive:
		for folder: String in DirAccess.get_directories_at(path):
			var _path: String = str(path, "/" if not path.ends_with("/") else "", folder)
			
			if EXCLUDED_DIRECTORIES.has(_path):
				continue
			
			files.append_array(find_scene_file_paths(_path))
	
	return files
