Files

60 lines
1.6 KiB
Kotlin

package com.hyperling.weather
import java.io.File
/**
* JVM Implementation of StorageBackend for Desktop use.
*/
class JvmStorageBackendImpl : StorageBackend {
private val STORAGE_DIR = File(System.getProperty("user.home"), ".nomadic-weather")
private val STORAGE_FILE = File(STORAGE_DIR, "locations.json")
init {
STORAGE_DIR.mkdirs()
}
override fun load(): List<LocationEntry> {
return try {
if (STORAGE_FILE.exists()) LocationSerializer.jsonToLocations(STORAGE_FILE.readText()) else emptyList()
} catch (e: Exception) {
emptyList()
}
}
override fun save(locations: List<LocationEntry>) {
try {
STORAGE_DIR.mkdirs()
STORAGE_FILE.writeText(LocationSerializer.locationsToJson(locations))
} catch (e: Exception) {}
}
override fun saveOne(location: LocationEntry) {
val ex = load().toMutableList()
val idx = ex.indexOfFirst { it == location }
if (idx >= 0) ex[idx] = location
else {
if (ex.size >= 8) ex.removeAt(0)
ex.add(location)
}
save(ex)
}
override fun delete(id: Long) {
save(load().filter { it.id != id })
}
}
/**
* JVM-specific platform initialization.
*/
class JvmPlatformInit : PlatformInit {
override fun initialize() {
val dir = File(System.getProperty("user.home"), ".nomadic-weather")
if (!dir.exists()) dir.mkdirs()
println("Nomadic Weather Desktop Initialized")
}
}
actual fun getPlatformStorage(): StorageBackend = JvmStorageBackendImpl()
actual fun getPlatformInit(): PlatformInit = JvmPlatformInit()