package eu.friedcutlet.yokan.data import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.domain.UserSettings import eu.friedcutlet.yokan.util.PlatformLock import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.launch /** * App-wide settings holder. Updates persist through [repository] and publish synchronously, so * text fields bound to a setting never lag; external writes (sync, restore, background jobs) are * picked up from the database snapshots. Safe to call from any thread. * * [onSchedulingChanged] runs after every [updateDb]/[updateSync]; the receiver decides whether the * periodic-task schedule actually changed. */ class SettingsStore( private val repository: YokanRepository, scope: CoroutineScope, private val onSchedulingChanged: () -> Unit, ) { // Serializes read-transform-write and publication, so a late snapshot can never overwrite a // newer value published by an update. private val lock = PlatformLock() private val _db = MutableStateFlow(repository.dbSettings()) val db: StateFlow = _db.asStateFlow() private val _user = MutableStateFlow(repository.settings()) val user: StateFlow = _user.asStateFlow() private val _sync = MutableStateFlow(repository.syncPreference()) val sync: StateFlow = _sync.asStateFlow() init { scope.launch { repository.snapshots .distinctUntilChanged { old, new -> old.settings === new.settings && old.syncPreferences === new.syncPreferences } .collect { lock.withLock { publishSettings(repository.dbSettings()) _sync.value = repository.syncPreference() } } } } fun updateDb(transform: (DbSettings) -> DbSettings) { lock.withLock { publishSettings(repository.updateDbSettings(transform)) } onSchedulingChanged() } fun update(transform: (UserSettings) -> UserSettings) { lock.withLock { repository.updateSettings(transform) publishSettings(repository.dbSettings()) } } fun updateSync(transform: (DbSyncPreference) -> DbSyncPreference) { lock.withLock { _sync.value = repository.updateSyncPreference(transform = transform) } onSchedulingChanged() } private fun publishSettings(settings: DbSettings) { _db.value = settings _user.value = settings.toDomain() } }