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

object UserRepository : Repository<User> {

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

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

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

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

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

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

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

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

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