generated from me/template-mit
50 lines
1.4 KiB
Kotlin
50 lines
1.4 KiB
Kotlin
package com.hyperling.weather
|
|
|
|
import java.io.File
|
|
|
|
/**
|
|
* File-based local storage manager for location entries (JVM/Desktop).
|
|
*/
|
|
class JvmStorageBackend : 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 existing = load().toMutableList()
|
|
val idx = existing.indexOfFirst { it == location }
|
|
if (idx >= 0) existing[idx] = location
|
|
else {
|
|
if (existing.size >= 8) existing.removeAt(0)
|
|
existing.add(location)
|
|
}
|
|
save(existing)
|
|
}
|
|
|
|
override fun delete(id: Long) {
|
|
save(load().filter { it.id != id })
|
|
}
|
|
}
|
|
|
|
actual fun LocationStorage.getStorage(): StorageBackend = JvmStorageBackend()
|