forked from thijooree/android
81 lines
2.8 KiB
Kotlin
81 lines
2.8 KiB
Kotlin
package sh.sar.basedbank.util
|
|
|
|
import android.content.Context
|
|
import org.json.JSONArray
|
|
import org.json.JSONObject
|
|
|
|
data class RecentPick(
|
|
val accountNumber: String,
|
|
val displayName: String,
|
|
val subtitle: String,
|
|
val colorHex: String,
|
|
val imageHash: String?,
|
|
val isProfileImage: Boolean
|
|
)
|
|
|
|
object RecentsCache {
|
|
|
|
private const val PREFS = "recents_cache"
|
|
private const val KEY = "contact_recents"
|
|
private const val MAX = 10
|
|
|
|
fun save(context: Context, pick: RecentPick) {
|
|
val existing = load(context).toMutableList()
|
|
existing.removeAll { it.accountNumber == pick.accountNumber }
|
|
existing.add(0, pick)
|
|
if (existing.size > MAX) existing.subList(MAX, existing.size).clear()
|
|
|
|
val arr = JSONArray()
|
|
for (r in existing) {
|
|
arr.put(JSONObject().apply {
|
|
put("accountNumber", r.accountNumber)
|
|
put("displayName", r.displayName)
|
|
put("subtitle", r.subtitle)
|
|
put("colorHex", r.colorHex)
|
|
if (r.imageHash != null) put("imageHash", r.imageHash)
|
|
put("isProfileImage", r.isProfileImage)
|
|
})
|
|
}
|
|
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
|
.edit().putString(KEY, arr.toString()).apply()
|
|
}
|
|
|
|
fun remove(context: Context, accountNumber: String) {
|
|
val updated = load(context).filter { it.accountNumber != accountNumber }
|
|
val arr = JSONArray()
|
|
for (r in updated) {
|
|
arr.put(JSONObject().apply {
|
|
put("accountNumber", r.accountNumber)
|
|
put("displayName", r.displayName)
|
|
put("subtitle", r.subtitle)
|
|
put("colorHex", r.colorHex)
|
|
if (r.imageHash != null) put("imageHash", r.imageHash)
|
|
put("isProfileImage", r.isProfileImage)
|
|
})
|
|
}
|
|
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
|
.edit().putString(KEY, arr.toString()).apply()
|
|
}
|
|
|
|
fun load(context: Context): List<RecentPick> {
|
|
val json = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
|
.getString(KEY, null) ?: return emptyList()
|
|
return try {
|
|
val arr = JSONArray(json)
|
|
(0 until arr.length()).map { i ->
|
|
val o = arr.getJSONObject(i)
|
|
RecentPick(
|
|
accountNumber = o.getString("accountNumber"),
|
|
displayName = o.getString("displayName"),
|
|
subtitle = o.getString("subtitle"),
|
|
colorHex = o.getString("colorHex"),
|
|
imageHash = o.optString("imageHash").takeIf { it.isNotBlank() },
|
|
isProfileImage = o.optBoolean("isProfileImage", false)
|
|
)
|
|
}
|
|
} catch (_: Exception) {
|
|
emptyList()
|
|
}
|
|
}
|
|
}
|