mirror of https://git.sr.ht/~oppen/ariane
68 lines
2.5 KiB
Kotlin
68 lines
2.5 KiB
Kotlin
package oppen.tva.io.history
|
|
|
|
import android.content.Context
|
|
import org.json.JSONArray
|
|
import org.json.JSONObject
|
|
|
|
/**
|
|
*
|
|
* This is a simple SharedPreferences based store for now because I don't want to get bogged down setting up Room at this point
|
|
*
|
|
*/
|
|
class SimplePrefsCache(context: Context): CacheInterface {
|
|
|
|
private val prefsKey = "oppen.tva.io.history.SimplePrefsCache.PREFS_KEY"
|
|
private val prefsCacheKey = "oppen.tva.io.history.SimplePrefsCache.PREFS_CACHE_KEY"
|
|
private val prefsActiveIndexKey = "oppen.tva.io.history.SimplePrefsCache.PREFS_ACTIVE_INDEX_KEY"
|
|
private val prefs = context.getSharedPreferences(prefsKey, Context.MODE_PRIVATE)
|
|
|
|
override fun getTabs(onTabs: (tabs: MutableList<Tab>, activeIndex: Int) -> Unit) {
|
|
val activeIndex = prefs.getInt(prefsActiveIndexKey, 0)
|
|
when (val rawJson = prefs.getString(prefsCacheKey, null)) {
|
|
null -> onTabs(arrayListOf(), activeIndex)
|
|
else -> {
|
|
val tabs = mutableListOf<Tab>()
|
|
val tabsJsonArray = JSONArray(rawJson)
|
|
val tabCount = tabsJsonArray.length()
|
|
for(index in 0 until tabCount){
|
|
val jsonTabObject = tabsJsonArray.getJSONObject(index)
|
|
val tabIndex = jsonTabObject.getInt("index")
|
|
val tab = Tab(tabIndex)
|
|
val jsonTabHistory = jsonTabObject.getJSONArray("history")
|
|
val historySize = jsonTabHistory.length()
|
|
for(historyIndex in 0 until historySize){
|
|
tab.add(jsonTabHistory.getString(historyIndex))
|
|
}
|
|
tabs.add(tab)
|
|
}
|
|
|
|
onTabs(tabs, activeIndex)
|
|
}
|
|
}
|
|
}
|
|
|
|
override fun update(tabs: List<Tab>, activeIndex: Int) {
|
|
val edit = prefs.edit()
|
|
edit.putInt(prefsActiveIndexKey, activeIndex)
|
|
edit.putString(prefsCacheKey, tabsToJson(tabs))
|
|
edit.apply()
|
|
}
|
|
|
|
private fun tabsToJson(tabs: List<Tab>): String {
|
|
val jsonArray = JSONArray()
|
|
tabs.forEach { tab ->
|
|
val jsonTab = JSONObject()
|
|
jsonTab.put("index", tab.index)
|
|
|
|
val jsonHistoryArray = JSONArray()
|
|
tab.history.forEach { uri ->
|
|
jsonHistoryArray.put(uri.toString())
|
|
}
|
|
jsonTab.put("history", jsonHistoryArray)
|
|
jsonArray.put(jsonTab)
|
|
}
|
|
val rawJsonArray = jsonArray.toString(5)
|
|
println("Raw tabs json to store:\n$rawJsonArray")
|
|
return rawJsonArray
|
|
}
|
|
} |