package de.kif.frontend.repository

import de.kif.common.ConstraintMap
import de.kif.common.Message
import de.kif.common.Repository
import de.kif.common.RepositoryType
import de.kif.common.model.Schedule
import de.kif.frontend.MessageHandler
import de.westermann.kobserve.event.EventHandler
import kotlinx.serialization.DynamicObjectParser
import kotlinx.serialization.list

object ScheduleRepository : Repository<Schedule> {

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

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

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

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

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

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

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

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

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

    suspend fun checkConstraints(): ConstraintMap {
        val json = repositoryGet("/api/constraints")
        return parser.parse(json, ConstraintMap.serializer())
    }

    suspend fun checkConstraintsFor(schedule: Schedule): ConstraintMap {
        val json = repositoryGet("/api/constraint/${schedule.id}")
        return parser.parse(json, ConstraintMap.serializer())
    }
}
