ManagerScriptConfig.kt (1813B) - raw


      1 package me.rhunk.snapenhance.scripting.impl
      2 
      3 import com.google.gson.JsonObject
      4 import me.rhunk.snapenhance.common.scripting.impl.ConfigInterface
      5 import me.rhunk.snapenhance.scripting.RemoteScriptManager
      6 import java.io.File
      7 
      8 class ManagerScriptConfig(
      9     private val remoteScriptManager: RemoteScriptManager
     10 ) : ConfigInterface() {
     11     private val configFile by lazy { File(remoteScriptManager.getModuleDataFolder(context.moduleInfo.name), "config.json") }
     12     private var config = JsonObject()
     13 
     14     override fun get(key: String, defaultValue: Any?): String? {
     15         return config[key]?.asString ?: defaultValue?.toString()
     16     }
     17 
     18     override fun set(key: String, value: Any?, save: Boolean) {
     19         when (value) {
     20             is Int -> config.addProperty(key, value)
     21             is Double -> config.addProperty(key, value)
     22             is Boolean -> config.addProperty(key, value)
     23             is Long -> config.addProperty(key, value)
     24             is Float -> config.addProperty(key, value)
     25             is Byte -> config.addProperty(key, value)
     26             is Short -> config.addProperty(key, value)
     27             else -> config.addProperty(key, value?.toString())
     28         }
     29 
     30         if (save) save()
     31     }
     32 
     33     override fun save() {
     34         configFile.writeText(config.toString())
     35     }
     36 
     37     override fun load() {
     38         runCatching {
     39             if (!configFile.exists()) {
     40                 save()
     41                 return@runCatching
     42             }
     43             config = remoteScriptManager.context.gson.fromJson(configFile.readText(), JsonObject::class.java)
     44         }.onFailure {
     45             context.runtime.logger.error("Failed to load config file", it)
     46             save()
     47         }
     48     }
     49 
     50     override fun deleteConfig() {
     51         configFile.delete()
     52     }
     53 
     54     override fun onInit() {
     55         load()
     56     }
     57 }