SnowyGUI/common/src/main/kotlin/fr/username404/snowygui/config/Configuration.kt

89 lines
3.0 KiB
Kotlin

package fr.username404.snowygui.config
import com.typesafe.config.Config
import com.typesafe.config.ConfigException
import com.typesafe.config.ConfigFactory.*
import com.typesafe.config.ConfigRenderOptions
import com.typesafe.config.ConfigValueFactory
import fr.username404.snowygui.ClickGui
import fr.username404.snowygui.Snowy
import fr.username404.snowygui.gui.feature.ButtonImpl
import io.github.config4k.extract
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import net.minecraft.client.Minecraft
import java.io.File
object Configuration {
private val file: File = File(Minecraft.getInstance().gameDirectory.absolutePath + File.separator + "snowy.conf")
private suspend fun writeConfig(c: Config) = coroutineScope {
launch {
file.writeText(
"""
Snowy {
${
c.root().render(
ConfigRenderOptions.defaults()
.setFormatted(true)
.setJson(false)
.setOriginComments(false)
).trimEnd()
}
}
""".trimIndent()
)
}
}
@JvmField
val obtained: Config = run {
var result: Config = empty()
with(file) {
if (!exists()) {
createNewFile()
setWritable(true)
setReadable(true)
} else try {
result = parseFile(file)
} catch (e: ConfigException) {
Snowy.logs.warn("Could not parse the snowy configuration file, the default configuration will be used instead.")
}
}
load(result).withFallback(
parseString(
"""
|Snowy {
| displayInitMessage = true
| riskyCheats = false
|}
""".trimMargin()
)
).extract<Config>("Snowy")
}.also {
runBlocking {
writeConfig(it)
}
}
val enabledFeatures: MutableMap<String, Boolean> = if (obtained.hasPath("enabledFeatures")) {
obtained.extract("enabledFeatures")
} else mutableMapOf()
init {
Runtime.getRuntime().addShutdownHook(
Thread {
runBlocking {
ClickGui.boxContext {
enabledFeatures.putAll(
buttons.map {
(it as ButtonImpl).run {
title.toString() to toggled
}
}
)
}
writeConfig(obtained.withValue("enabledFeatures", ConfigValueFactory.fromMap(enabledFeatures))).join() // TODO Fix formatting of enabledFeatures
}
}
)
}
}