package de.kif.backend.util

import de.kif.backend.repository.*
import de.kif.common.*
import de.kif.common.RepositoryType
import io.ktor.http.cio.websocket.Frame
import io.ktor.http.cio.websocket.readText
import io.ktor.routing.Route
import io.ktor.websocket.WebSocketServerSession
import io.ktor.websocket.webSocket
import kotlinx.coroutines.channels.ClosedReceiveChannelException

object PushService {

    var clients: List<WebSocketServerSession> = emptyList()

    suspend fun notify(type: MessageType, repository: RepositoryType, id: Long) {
        try {
            val data = Message(type, repository, id).stringify()
            for (client in clients) {
                client.outgoing.send(Frame.Text(data))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

fun Route.pushService() {
    webSocket {
        PushService.clients += this

        try {
            while (true) {
                val text = (incoming.receive() as Frame.Text).readText()
                println("onMessage($text)")
                outgoing.send(Frame.Text(text))
            }
        } catch (_: ClosedReceiveChannelException) {
            PushService.clients -= this
        } catch (e: Throwable) {
            println("onFailure ${closeReason.await()}")
            e.printStackTrace()
            PushService.clients -= this
        }
    }

    RoomRepository.registerPushService()
    ScheduleRepository.registerPushService()
    TrackRepository.registerPushService()
    UserRepository.registerPushService()
    WorkGroupRepository.registerPushService()
    PostRepository.registerPushService()
}
