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

object TrackRepository : Repository<Track> {

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

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

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

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

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

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

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

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

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