package de.kif.backend.repository

import de.kif.backend.Configuration
import de.kif.backend.util.PushService
import de.kif.common.MessageType
import de.kif.common.RepositoryType
import de.westermann.kobserve.event.EventHandler
import kotlinx.coroutines.runBlocking

object AnnouncementRepository {

    val onUpdate = EventHandler<Unit>()

    private val file = Configuration.Path.announcementPath.toFile()

    private var announcement = ""

    fun setAnnouncement(value: String) {
        val str = value.replace("\n", " ").trim()
        if (announcement == str) return

        announcement = str
        try {
            file.writeText(str)
        } catch (e: Exception) {

        }

        onUpdate.emit(Unit)
    }

    fun getAnnouncement(): String {
        return announcement
    }

    fun registerPushService() {
        onUpdate {
            runBlocking {
                PushService.notify(MessageType.UPDATE, RepositoryType.ANNOUNCEMENT, 0L)
            }
        }
    }

    init {
        try {
            if (!file.exists()) {
                file.createNewFile()
            }
            announcement = file.readText().trim()
        } catch (e: Exception) {
        }
    }
}
