package uk.co.nickthecoder.gamescupboard.client
import com.soywiz.korge.Korge
import com.soywiz.korim.format.readBitmap
import com.soywiz.korio.file.std.resourcesVfs
import com.soywiz.korma.geom.Anchor
import com.soywiz.korma.geom.ScaleMode
import io.ktor.client.*
import io.ktor.client.plugins.websocket.*
import io.ktor.websocket.*
import kotlinx.serialization.json.Json
import uk.co.nickthecoder.gamescupboard.common.stageHeight
import uk.co.nickthecoder.gamescupboard.common.stageWidth
val json = Json
lateinit var gamesCupboardClient: GamesCupboardClient
fun localPlayer() = gamesCupboardClient.localPlayer
fun localPlayerId() = gamesCupboardClient.localPlayer.id
fun isSpectator() = gamesCupboardClient.localPlayer.isSpectator
// Main entry point
suspend fun main() = Korge(
title = "Games Cupboard",
icon = resourcesVfs["icon.png"].readBitmap(),
width = stageWidth, height = stageHeight,
bgcolor = windowBackground,
scaleMode = ScaleMode.FIT,
scaleAnchor = Anchor.MIDDLE_LEFT,
clipBorders = false
) {
val gameId = Parameters["gameId"] ?: 0
val seatNumber = Parameters["seat"] ?: 0 // NOTE, if this seat was taken, then another will be chosen.
val wantsToBeASpectator = Parameters["spectate"] == "true"
val code = Parameters["code"]
val codeSuffix = if (code.isNullOrBlank()) "" else "&code=$code"
val host = Parameters.host
val port = Parameters.port
println("Joining Game#$gameId on $host:$port wantsToBeASpectator=$wantsToBeASpectator")
val webSocketPath = "/websocket/${gameId}?" + if (wantsToBeASpectator) {
"spectate=true$codeSuffix"
} else {
"seat=$seatNumber$codeSuffix"
}
HttpClient {
install(WebSockets)
}.ws(
host = host, port = port, path = webSocketPath
) {
try {
gamesCupboardClient = GamesCupboardClient(theStage = this@Korge, session = this@ws)
gamesCupboardClient.listen()
} catch (e: Throwable) {
e.printStackTrace()
} finally {
try {
println("Closing websocket")
close() // Close the websocket session.
println("Closed websocket")
} catch (_: Throwable) {
// Ignore errors
}
try {
// stage.gameWindow.close()
} catch (_: Throwable) {
// Do nothing
}
}
println("End of session block") // AltF4 stops here, with a CancellationException.
}
println("End of main")
}