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, activeIndex: Int) -> Unit) { val activeIndex = prefs.getInt(prefsActiveIndexKey, 0) when (val rawJson = prefs.getString(prefsCacheKey, null)) { null -> onTabs(arrayListOf(), activeIndex) else -> { val tabs = mutableListOf() 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, activeIndex: Int) { val edit = prefs.edit() edit.putInt(prefsActiveIndexKey, activeIndex) edit.putString(prefsCacheKey, tabsToJson(tabs)) edit.apply() } private fun tabsToJson(tabs: List): 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 } }