@tool
extends AbstractRoomRepo
class_name RoomRepoHTTP

const BASE_URL = "http://localhost:5004"

signal rooms_loaded(rooms: Array[RoomEntity])
signal request_failed(error_message: String)

const ROOM_ENDPOINT = "/room/"

var _http_client := HTTPTalkpalClient.new(BASE_URL)

func _init():
	add_child(_http_client)
	_http_client.request_failed.connect(_on_request_failed)

func list_rooms() -> Array[RoomEntity]:
	var result = await _http_client.request(ROOM_ENDPOINT, HTTPClient.METHOD_GET)
	if result is Array:
		var rooms = _parse_room_list(result)
		return rooms
	else:
		emit_signal("request_failed", "Failed to load rooms")
		return []

func get_room(id: String) -> RoomEntity:
	var rooms = await list_rooms()

	for room in rooms:
		if room.id == id:
			return room

	return null

func _parse_room_list(data: Array) -> Array[RoomEntity]:
	var rooms: Array[RoomEntity] = []
	for item in data:
		var room = RoomEntity.new()
		room.id = item.get("id")
		room.title = item.get("title")
		rooms.append(room)
	return rooms

func _on_request_failed(error_message: String):
	emit_signal("request_failed", error_message)
