@tool
extends AbstractReservationRepo
class_name LocalReservationRepo

const uuid_util = preload('res://addons/uuid/uuid.gd')

var _reservations = {}

func _ready():
	connected.emit()

func create_reservation(dto: CreateReservationDTO):
	var entity = ReservationEntity.new()

	entity.id = uuid_util.v4()
	entity.title = dto.title
	entity.description = dto.description
	entity.room_id = dto.room_id
	entity.creator = dto.creator
	entity.date = dto.date
	entity.start_time = dto.start_time.duplicate(true)
	entity.finish_time = dto.finish_time.duplicate(true)
	entity.color = dto.color

	_reservations[entity.id] = entity

func cancel_reservation(reservation_id):
	_reservations[reservation_id].queue_free()
	_reservations.erase(reservation_id)

func change_reservation(reservation_id, dto: UpdateReservationDTO):
	var entity = _reservations[reservation_id]

	entity.title = dto.title
	entity.description = dto.description
	entity.room_id = dto.room_id
	entity.creator = dto.creator
	entity.start_time = dto.start_time.duplicate(true)
	entity.finish_time = dto.finish_time.duplicate(true)

func get_reservation(reservation_id):
	return _reservations[reservation_id]

func list_reservations(filters: Dictionary = {})  -> Array:
	var reservations = []

	for key in _reservations:
		reservations.append(_reservations[key])

	reservations.sort_custom(self._compare_reservations_by_start_time)

	return reservations

func _compare_reservations_by_start_time(a: ReservationEntity, b: ReservationEntity) -> int:
	var time_a = a.start_time["hours"] * 60 + a.start_time["minutes"]
	var time_b = b.start_time["hours"] * 60 + b.start_time["minutes"]

	return time_a < time_b
