package com.cottondb.android.platform import android.content.Context import com.cottondb.android.core.CottonCalling import com.cottondb.android.day.alarms.Alarm import com.cottondb.android.day.alarms.AlarmMutation import com.cottondb.android.day.alarms.AlarmsRead import com.cottondb.android.day.alarms.AlarmsRepository import com.cottondb.android.reminders.NotificationPermission import com.cottondb.android.reminders.NotificationPrefs import com.cottondb.android.reminders.ReminderCentre import com.cottondb.android.reminders.ReminderPass import java.time.Clock import java.time.ZoneId import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext data class ScheduledNotificationState( val prefs: NotificationPrefs, val permission: NotificationPermission, val exactAlarms: Boolean, val error: String? = null, ) internal interface ScheduledAlarmRepository { suspend fun refresh(): AlarmsRead? suspend fun setEnabled(id: String, enabled: Boolean): AlarmMutation } internal interface ScheduledAlarmPlatform { fun exactAlarmAllowed(): Boolean fun reconcile( alarms: List, zone: ZoneId, prefs: NotificationPrefs, permission: NotificationPermission, ): AlarmScheduleOutcome } internal data class ScheduledNotificationDependencies( val prefs: NotificationPrefsPersistence, val reminders: ReminderCentre, val alarms: ScheduledAlarmRepository, val scheduler: ScheduledAlarmPlatform, val permission: (NotificationPrefs) -> NotificationPermission, val ensurePeriodic: () -> Unit, val cancelPeriodic: () -> Unit, val stopAlarmService: () -> Unit, ) /** One session-owned scheduling authority. Jobs, foreground and database events share this pass. */ class ScheduledNotifications internal constructor( private val context: Context, core: CottonCalling, scope: CoroutineScope, private val report: (String) -> Unit, private val clock: Clock, private val dependencies: ScheduledNotificationDependencies, ) { constructor( context: Context, core: CottonCalling, scope: CoroutineScope, report: (String) -> Unit, clock: Clock = Clock.systemUTC(), ) : this(context, core, scope, report, clock, productionDependencies(context, core, clock)) private val pass = ReminderPass(core, dependencies.reminders, clock) private val mutex = Mutex() private var retired = false private val requests = Channel(Channel.CONFLATED) private val _state = MutableStateFlow(null) val state = _state.asStateFlow() init { scope.launch { for (ignored in requests) { try { reconcile() } catch (cancelled: CancellationException) { throw cancelled } catch (failure: Throwable) { report(failure.message ?: "Notifications could not be scheduled.") } } } } fun request() { requests.trySend(Unit) } suspend fun recordPermissionRequest() = withContext(Dispatchers.IO) { mutex.withLock { check(!retired) { "This database is closing." } dependencies.prefs.save(dependencies.prefs.load().copy(askedAt = clock.instant().toString())) } } suspend fun reconcile() = withContext(Dispatchers.IO) { mutex.withLock { if (retired) return@withLock val prefs = dependencies.prefs.load() val permission = dependencies.permission(prefs) val capability = ScheduledNotificationState(prefs, permission, dependencies.scheduler.exactAlarmAllowed()) _state.value = capability try { val zone = ZoneId.systemDefault() val reminderResult = pass.run(zone.id, prefs, permission) check(reminderResult.refusal == null) { "Reminders could not be reconciled: ${reminderResult.refusal}." } val read = dependencies.alarms.refresh() ?: error("Alarms could not be read for scheduling.") val result = dependencies.scheduler.reconcile(read.alarms, zone, prefs, permission) val fired = when (result) { is AlarmScheduleOutcome.Applied -> result.firedOnce is AlarmScheduleOutcome.Partial -> result.firedOnce is AlarmScheduleOutcome.Refused -> error(result.message) } // Keep delivered history until the durable write succeeds. A failed write retries // on the next pass; it must never turn a fired one-shot into tomorrow's alarm. for (id in fired) { val update = dependencies.alarms.setEnabled(id, false) if (update is AlarmMutation.Failure) error(update.message) } if (result is AlarmScheduleOutcome.Partial) error(result.message) dependencies.ensurePeriodic() } catch (failure: Throwable) { if (failure is CancellationException) throw failure _state.value = capability.copy(error = failure.message ?: "Notifications could not be scheduled.") throw failure } } } /** Clear platform rows for a failed or abandoned boot without retiring the session-owned core. */ suspend fun clearPlatform() = clearPlatform(retiring = false) /** Cancel platform work before the replica goes away. Future writes are refused permanently. */ suspend fun retire() = clearPlatform(retiring = true) private suspend fun clearPlatform(retiring: Boolean) = withContext(Dispatchers.IO) { mutex.withLock { if (retiring) { this@ScheduledNotifications.retired = true requests.close() } dependencies.reminders.cancel(dependencies.reminders.heldIdentifiers()) val result = dependencies.scheduler.reconcile( emptyList(), ZoneId.systemDefault(), NotificationPrefs(enabled = false), NotificationPermission.Denied, ) check(result is AlarmScheduleOutcome.Applied) { "Android alarms could not be cleared before leaving." } dependencies.cancelPeriodic() dependencies.stopAlarmService() } } private companion object { fun productionDependencies( context: Context, core: CottonCalling, clock: Clock, ): ScheduledNotificationDependencies { val exact = AndroidExactAlarmPlatform(context) val repository = AlarmsRepository(core) return ScheduledNotificationDependencies( prefs = NotificationPrefsStore(context), reminders = AndroidReminderCentre(context), alarms = object : ScheduledAlarmRepository { override suspend fun refresh(): AlarmsRead? = repository.refresh() override suspend fun setEnabled(id: String, enabled: Boolean): AlarmMutation = repository.setEnabled(id, enabled) }, scheduler = object : ScheduledAlarmPlatform { private val scheduler = AndroidAlarmScheduler(AndroidAlarmLedgerStore(context), exact, clock) override fun exactAlarmAllowed(): Boolean = exact.exactAlarmAllowed() override fun reconcile(alarms: List, zone: ZoneId, prefs: NotificationPrefs, permission: NotificationPermission): AlarmScheduleOutcome = scheduler.reconcile(alarms, zone, prefs, permission) }, permission = { prefs -> notificationPermission(context, prefs) }, ensurePeriodic = { AlarmDeliveryJob.ensurePeriodic(context) }, cancelPeriodic = { AlarmDeliveryJob.cancel(context) }, stopAlarmService = { context.stopService(android.content.Intent(context, AndroidAlarmService::class.java)) }, ) } } }