package de.kif.frontend.repository

import de.kif.common.RepositoryType
import de.kif.frontend.MessageHandler
import de.westermann.kobserve.event.EventHandler
import kotlinx.serialization.DynamicObjectParser

object AnnouncementRepository {

    private val prefix = js("prefix")

    val onUpdate = EventHandler<Unit>()

    private val parser = DynamicObjectParser()

    suspend fun getAnnouncement(): String {
        val json = repositoryGet("$prefix/api/announcement") ?: return ""
        return json as String
    }

    suspend fun setAnnouncement(value: String){
        return repositoryPost("$prefix/api/announcement", value)
            ?: throw IllegalStateException("Cannot set announcement!")
    }

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

        override fun onCreate(id: Long) {}

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

        override fun onDelete(id: Long) {}
    }
}
