class_name LoadSingleton extends Node

signal loadStart(scenePath:String, loadId:int)
signal loadEnd(scenePath:String, loadId:int, resource:Resource)
signal loadError(scenePath:String, loadId:int, error:String)
signal loadProgress(scenePath:String, loadId:int, progress:float)

var watchingIds:Array[int] = []

func _process(delta: float) -> void:
  var wIds = watchingIds.duplicate()
  for watchId in wIds:
    var status = ResourceLoader.load_threaded_get_status(watchId)
    if status == ResourceLoader.ThreadLoadStatus.THREAD_LOAD_LOADED:
      watchingIds.erase(watchId)
      var resource = ResourceLoader.load_threaded_get(watchId)
      loadEnd.emit(watchId, resource)
    elif status == ResourceLoader.ThreadLoadStatus.THREAD_LOAD_FAILED:
      watchingIds.erase(watchId)
      loadError.emit(watchId, "Error loading resource.")
    elif status == ResourceLoader.ThreadLoadStatus.THREAD_LOAD_INVALID_RESOURCE:
      watchingIds.erase(watchId)
      loadError.emit(watchId, "Invalid Resource.")
    elif status == ResourceLoader.ThreadLoadStatus.THREAD_LOAD_IN_PROGRESS:
      loadProgress.emit(watchId, 0.0)
  pass

func load(scenePath:String) -> int:
  var loadId = ResourceLoader.load_threaded_request(scenePath)
  watchingIds.append(loadId)
  loadStart.emit(scenePath, loadId)
  return loadId