package com.correx.apps.cli.ws

import io.ktor.client.HttpClient
import io.ktor.client.plugins.websocket.webSocket
import io.ktor.websocket.Frame
import io.ktor.websocket.WebSocketSession
import io.ktor.websocket.readText

class CliWsClient(private val httpClient: HttpClient) {
    suspend fun sessionStream(
        host: String,
        port: Int,
        sessionId: String,
        onMessage: suspend (WebSocketSession, String) -> Boolean,
    ) {
        httpClient.webSocket(host = host, port = port, path = "/sessions/$sessionId/stream") {
            for (frame in incoming) {
                if (frame is Frame.Text) {
                    val keepGoing = onMessage(this, frame.readText())
                    if (!keepGoing) break
                }
            }
        }
    }
}
