extends Node

var queue = ResourceQueue.new()
var target_scene = null
var loading_text = null

var loader = preload("res://Scenes/Loader.tscn")

onready var netgame = $"/root/Multiplayer"

func _ready() -> void:
	var threads_supported = true
	if OS.get_name() == "HTML5":
		threads_supported = false
	queue.start(threads_supported)

func enter_loader() -> void:
	get_tree().change_scene_to(loader)

func load_scene(scene_path: String, dependencies: Array) -> void:
	if queue.threaded:
		target_scene = scene_path
		queue.queue_resource(scene_path)
		for dep in dependencies:
			queue.queue_resource(dep)
	else:
		get_tree().change_scene(scene_path)

func _physics_process(_delta: float) -> void:
	if queue.threaded:
		if target_scene != null:
			var remaining = queue.pending.size()
			for path in queue.pending:
				if queue.is_ready(path):
					remaining -= 1
			if remaining == 0:
				get_tree().change_scene_to(queue.get_resource(target_scene))
				target_scene = null

func get_progress() -> String:
	if loading_text != null:
		return loading_text
	var count = queue.pending.size()
	if count == 0:
		return "Reticulating splines"
	var current = 0
	for path in queue.pending:
		current += queue.get_progress(path)
	return "Loading scene (%.0f%%)" % (current/count*100)
