extends Node

signal GameStarted
signal MapChanged(map_id: Enums.MapIds)

@export var initial_map_id: Enums.MapIds

@onready var world: Node2D = $"../World"

# Public Methods
func InstantiateTitleScreen() -> void:
	var map_scene := MapLoader.GetMap(Enums.MapIds.TITLE_SCREEN)
	var map := map_scene.instantiate()
	world.add_child(map)
	
	if !map.is_node_ready():
		await map.ready
	
	map.connect("GameStarted", _on_title_screen_game_started_clicked)
	
	_connect_loading_zone_transporters()
	MapChanged.emit(Enums.MapIds.TITLE_SCREEN)


func InstantiateInitialMap() -> void:
	var map_scene := MapLoader.GetMap(initial_map_id)
	var map := map_scene.instantiate()
	world.add_child(map)
	
	if !map.is_node_ready():
		await map.ready
	
	_connect_loading_zone_transporters()
	MapChanged.emit(initial_map_id)


# Private Methods
func _on_title_screen_game_started_clicked() -> void:
	GameStarted.emit()
	_on_map_transition_queued(initial_map_id, "")


func _on_map_transition_queued(map_id: Enums.MapIds, marker_name: String) -> void:
	print("Map Transition Queued: %s" % [Enums.MapIds.keys()[map_id]])
	var map_scene := MapLoader.GetMap(map_id)
	MapLoader.SetSpawnMarker(marker_name)
	
	for child in world.get_children():
		child.queue_free()
		await child.tree_exited
	
	var map := map_scene.instantiate()
	world.call_deferred("add_child", map)
	await map.ready
	
	_connect_loading_zone_transporters()
	MapChanged.emit(map_id)


func _connect_loading_zone_transporters() -> void:
	var loading_zone_transporters := GroupUtils.GetAllLoadingZoneTransporters()
	print("Loading Zones: %d" % len(loading_zone_transporters))
	
	for transporter in loading_zone_transporters:
		transporter.MapTransitionQueued.connect(_on_map_transition_queued)
