extends Control

signal room_selected(title: String, id: String)

@onready var _main: Main = get_tree().get_current_scene()
@onready var _rooms_menu := $RoomsMenu

var _rooms : Array[RoomEntity] = []

func _ready():
	_connect_signals()

	await get_tree().create_timer(0.1, false).timeout
	_load_rooms()

func _load_rooms():
	var room_repo = _main.get_room_repo()
	if room_repo.get_selected_room():
		return
		
	_rooms_menu.clear()

	var rooms = await room_repo.list_rooms()
	for room in rooms:
		_rooms.append(room)
		_rooms_menu.add_item(room.title)

	if len(rooms) < 0:
		print('Not enough rooms') 

func _connect_signals():
	_rooms_menu.item_clicked.connect(_on_room_selected)

func _on_room_selected(idx, text):
	room_selected.emit(_rooms[idx].title, _rooms[idx].id)
	_main.go_to_previous_page(true)

func update():
	_rooms_menu.deselect_all()
