package ch.dissem.yaep.ui.common

import ch.dissem.yaep.domain.Game
import io.github.oshai.kotlinlogging.KotlinLogging
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
import kotlin.io.path.Path
import kotlin.io.path.createFile
import kotlin.io.path.isDirectory
import kotlin.io.path.writeText
import kotlin.time.Clock
import kotlin.time.ExperimentalTime

private val log = KotlinLogging.logger {}

@OptIn(ExperimentalTime::class)
actual fun CoroutineScope.logGame(game: Game, dispatcher: CoroutineContext) {
    launch(dispatcher) {
        val dirName = """${System.getProperty("user.home")}/.yaep"""
        val dir = Path(dirName)
        if (dir.isDirectory()) {
            val fileName = "$dirName/${Clock.System.now()}.yaep"
            Path(fileName)
                .createFile()
                .writeText(game.toString())
            log.info { "Saved game to $fileName" }
        } else {
            log.debug { "Yaep data directory does not exist or is not a directory: $dir" }
            log.debug { "Game: $game" }
        }
    }
}