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.WorkGroup
import de.kif.frontend.MessageHandler
import de.westermann.kobserve.event.EventHandler
import kotlinx.serialization.DynamicObjectParser
import kotlinx.serialization.list

object WorkGroupRepository : Repository<WorkGroup> {

    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): WorkGroup? {
        val json = repositoryGet("/api/workgroup/$id") ?: return null
        return parser.parse(json, WorkGroup.serializer())
    }

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

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

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

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

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

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

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

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