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:
	queue.start(netgame.gotm_mode)

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

func load_scene(scene_path: String, dependencies: Array) -> void:
	if not netgame.gotm_mode:
		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 not netgame.gotm_mode:
		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 (" + str(round(current/count*100)) + "%)"
