package com.correx.apps.cli.commands

import com.correx.apps.cli.DEFAULT_PORT
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.options.default
import com.github.ajalt.clikt.parameters.options.option
import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.request.post
import io.ktor.client.statement.bodyAsText
import kotlinx.coroutines.runBlocking

class UndoCommand : CliktCommand(name = "undo") {
    private val sessionId by argument("SESSION_ID")
    private val host by option("--host").default("localhost")
    private val port by option("--port").default("$DEFAULT_PORT")

    override fun run(): Unit = runBlocking {
        val portInt = port.toIntOrNull() ?: DEFAULT_PORT
        val client = HttpClient(CIO)
        try {
            val response = client.post("http://$host:$portInt/sessions/$sessionId/undo")
            echo(response.bodyAsText())
        } finally {
            client.close()
        }
    }
}
