extends Node

var loading_screen_scene: = preload('res://ui/loading_screen.tscn')

var loading_screen_instance: LoadingScreen

var _loading: String = ""

var progress: Array[float] = []

func _init() -> void:
	process_mode = PROCESS_MODE_ALWAYS

func _ready() -> void:
	loading_screen_instance = loading_screen_scene.instantiate()


func load_scene(path: String):
	get_tree().paused = true
	ResourceLoader.load_threaded_request(path, "", true)
	var status := ResourceLoader.load_threaded_get_status(path, progress)
	show_loading_screen()
	if status != ResourceLoader.THREAD_LOAD_LOADED:
		_loading = path



func show_loading_screen():
	if not loading_screen_instance.get_parent(): add_child(loading_screen_instance)


func hide_loading_screen():
	if not loading_screen_instance: return
	await loading_screen_instance.fade_out()
	if loading_screen_instance.get_parent(): loading_screen_instance.get_parent().remove_child(loading_screen_instance)

func _process(_delta: float) -> void:
	if _loading == "": return

	var status := ResourceLoader.load_threaded_get_status(_loading, progress)
	if status != ResourceLoader.THREAD_LOAD_LOADED: return

	var resource : PackedScene = ResourceLoader.load_threaded_get(_loading)
	get_tree().change_scene_to_packed(resource)
	hide_loading_screen()
	get_tree().paused = false
	_loading = ""
