package de.kif.frontend.repository

import de.kif.common.Message
import de.kif.common.Repository
import de.kif.common.RepositoryType
import de.kif.common.model.Room
import de.kif.frontend.MessageHandler
import de.westermann.kobserve.event.EventHandler
import kotlinx.serialization.DynamicObjectParser
import kotlinx.serialization.list

object RoomRepository : Repository<Room> {

    override val onCreate = EventHandler<Long>()
    override val onUpdate = EventHandler<Long>()
    override val onDelete = EventHandler<Long>()

    private val parser = DynamicObjectParser()

    override suspend fun get(id: Long): Room? {
        val json = repositoryGet("/api/room/$id") ?: return null
        return parser.parse(json, Room.serializer())
    }

    override suspend fun create(model: Room): Long {
        return repositoryPost("/api/rooms", Message.json.stringify(Room.serializer(), model))
            ?: throw IllegalStateException("Cannot create model!")
    }

    override suspend fun update(model: Room) {
        if (model.id == null) throw IllegalStateException("Cannot update model which was not created!")
        repositoryPost("/api/room/${model.id}", Message.json.stringify(Room.serializer(), model))
    }

    override suspend fun delete(id: Long) {
        repositoryPost("/api/room/$id/delete")
    }

    override suspend fun all(): List<Room> {
        val json = repositoryGet("/api/rooms") ?: return emptyList()
        return parser.parse(json, Room.serializer().list)
    }

    val handler = object : MessageHandler(RepositoryType.ROOM) {

        override fun onCreate(id: Long) = onCreate.emit(id)

        override fun onUpdate(id: Long) = onUpdate.emit(id)

        override fun onDelete(id: Long) = onDelete.emit(id)
    }
}
