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

object PostRepository : Repository<Post> {

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

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

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

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

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

    suspend fun htmlByUrl(url: String): String {
        return repositoryRawGet("/api/p/$url")
    }

    suspend fun render(data: String): String {
        return repositoryPost("/api/render", data)
    }

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

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

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

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