extends Node

## SceneID -> ReedScene
var _scene_map: Dictionary = {}
## SceneID -> ReedSceneIDComp
var _scene_id_comp_map: Dictionary[int, ReedSceneID] = {}

signal scene_registered(scene_id: int, scene: ReedScene)
signal scene_unregistered(scene_id: int)

func register_scene(scene: ReedScene) -> bool:
	if scene == null:
		return false

	var id_comp := scene.get_scene_id_comp()
	if id_comp == null:
		push_warning("[SceneRegistry] Scene has no ReedSceneID.")
		return false

	return register_scene_with_id(id_comp.scene_id, scene, id_comp)

func register_scene_with_id(
	scene_id: int,
	scene: ReedScene,
	id_comp: ReedSceneID = null
) -> bool:
	if scene_id < 0:
		push_warning("[SceneRegistry] Reject invalid SceneID: %d" % scene_id)
		return false

	if _scene_map.has(scene_id):
		push_warning("[SceneRegistry] SceneID already registered: %d" % scene_id)
		return false

	_scene_map[scene_id] = scene

	if id_comp != null:
		_scene_id_comp_map[scene_id] = id_comp

	if scene.debug_log:
		print("[SceneRegistry] Registered Scene:", scene_id, scene.name)

	return true


func unregister_scene(scene: ReedScene) -> void:
	if scene == null:
		return

	var id_comp := scene.get_node_or_null("SceneID") as ReedSceneID
	if id_comp == null:
		return

	var scene_id := id_comp.scene_id
	if not _scene_map.has(scene_id):
		return

	_scene_map.erase(scene_id)
	_scene_id_comp_map.erase(scene_id)


func get_scene(scene_id: int) -> ReedScene:
	return _scene_map.get(scene_id, null)
