package com.vgmlr.kiln
import android.content.Context
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import androidx.core.content.edit
class KilnPrefs private constructor(context: Context) {
private val store =
context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
private val _defaultAccountId = MutableStateFlow(store.getLong(KEY_DEFAULT, NO_ACCOUNT))
val defaultAccountId: StateFlow<Long> = _defaultAccountId
private val _loadDefaultOnStart = MutableStateFlow(store.getBoolean(KEY_LOAD_DEFAULT, false))
val loadDefaultOnStart: StateFlow<Boolean> = _loadDefaultOnStart
fun setDefaultAccount(id: Long) {
store.edit { putLong(KEY_DEFAULT, id) }
_defaultAccountId.value = id
}
fun setLoadDefaultOnStart(enabled: Boolean) {
store.edit { putBoolean(KEY_LOAD_DEFAULT, enabled) }
_loadDefaultOnStart.value = enabled
}
fun alertDay(key: String, accountId: Long): Long = store.getLong(key + accountId, NO_DAY)
fun setAlertDay(key: String, accountId: Long, epochDay: Long) =
store.edit { putLong(key + accountId, epochDay) }
fun clearAlertDay(key: String, accountId: Long) = store.edit { remove(key + accountId) }
fun stopPeriodRun(accountId: Long) = setAlertDay(
KEY_PERIOD_DISMISSED, accountId, alertDay(KEY_PERIOD_ANCHOR, accountId)
)
companion object {
const val NO_ACCOUNT = 0L
const val NO_DAY = Long.MIN_VALUE
const val KEY_PMS_DAY = "pms_day_"
const val KEY_PERIOD_DAY = "period_day_"
const val KEY_PERIOD_ANCHOR = "period_anchor_"
const val KEY_PERIOD_DISMISSED = "period_dismissed_"
private const val PREFS = "kiln_prefs"
private const val KEY_DEFAULT = "default_account"
private const val KEY_LOAD_DEFAULT = "load_default_on_start"
@Volatile private var instance: KilnPrefs? = null
fun get(context: Context): KilnPrefs =
instance ?: synchronized(this) {
instance ?: KilnPrefs(context).also { instance = it }
}
}
}