package com.cottondb.android import com.cottondb.android.core.CottonCalling import com.cottondb.android.navigation.Route import com.cottondb.android.work.money.MoneyAccountRead import com.cottondb.android.work.money.MoneyRead import com.cottondb.android.work.money.MoneyReadState import com.cottondb.android.work.money.MoneyRepository import com.cottondb.android.work.money.MoneyStatementRead import com.cottondb.android.work.money.MoneyTransactionRead import com.cottondb.android.work.money.moneyToday import java.time.Clock import java.time.ZoneId import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch /** * Retains the independent read models represented by the current Accounts navigation stack. * * Every visit has a child scope. Popping its route cancels that scope, including its eager state * collection and any refresh it started, so a late core reply cannot republish into a retired UI. */ class MoneyModels( private val core: CottonCalling, private val clock: Clock, private val zone: ZoneId, private val scope: CoroutineScope, ) { private val repository = MoneyRepository(core) private var overview: MoneyOverviewVisit? = null private val accounts = mutableMapOf() private val statements = mutableMapOf() private val transactions = mutableMapOf() private val deletions = mutableMapOf() private val lifetimes = mutableMapOf() fun overview(): MoneyOverviewVisit = overview ?: owned { visitScope -> MoneyOverviewVisit(repository, clock, zone, visitScope) }.also { overview = it } fun account(id: String): MoneyAccountVisit = accounts.getOrPut(id) { owned { visitScope -> MoneyAccountVisit(id, repository, clock, zone, visitScope) } } fun statement(id: String): MoneyStatementVisit = statements.getOrPut(id) { owned { visitScope -> MoneyStatementVisit(id, repository, visitScope) } } fun transaction(id: String): MoneyTransactionVisit = transactions.getOrPut(id) { owned { visitScope -> MoneyTransactionVisit(id, repository, visitScope) } } fun deletion(id: String): MoneyDeleteVisit = deletions.getOrPut(id) { owned { visitScope -> MoneyDeleteVisit(id, core, visitScope) } } private fun owned(create: (CoroutineScope) -> T): T { val lifetime = SupervisorJob(scope.coroutineContext[Job]) return create(CoroutineScope(scope.coroutineContext + lifetime)).also { lifetimes[it] = lifetime } } fun retain(routes: List) { if (Route.Money !in routes) overview?.let(::retire).also { overview = null } val accountIds = routes.filterIsInstance().map { it.id }.toSet() val statementIds = routes.filterIsInstance().map { it.id }.toSet() val transactionIds = routes.filterIsInstance().map { it.id }.toSet() accounts.keys.filterNot(accountIds::contains).forEach { accounts.remove(it)?.let(::retire) } statements.keys.filterNot(statementIds::contains).forEach { statements.remove(it)?.let(::retire) } transactions.keys.filterNot(transactionIds::contains).forEach { transactions.remove(it)?.let(::retire) } deletions.keys.filterNot(transactionIds::contains).forEach { deletions.remove(it)?.let(::retire) } } private fun retire(visit: MoneyVisit) { visit.close() lifetimes.remove(visit)?.cancel() } } interface MoneyVisit : AutoCloseable abstract class MoneyReadVisit( private val id: String?, protected val scope: CoroutineScope, source: Flow>, initial: MoneyReadState, private val unavailable: String, ) : MoneyVisit { private var closed = false val state: StateFlow> = if (id?.trim()?.isNotEmpty() == false) { kotlinx.coroutines.flow.MutableStateFlow>(MoneyReadState.Error(unavailable, null)) } else { source.stateIn(scope, SharingStarted.Eagerly, initial) } /** Starts at most while this route visit remains retained. */ fun refresh(): Job = scope.launch { if (!closed && id?.trim()?.isNotEmpty() != false) refreshRead() } protected abstract suspend fun refreshRead() override fun close() { closed = true scope.cancel() } } class MoneyOverviewVisit internal constructor( private val repository: MoneyRepository, private val clock: Clock, private val zone: ZoneId, scope: CoroutineScope, ) : MoneyReadVisit(null, scope, repository.money, repository.money.value, "Accounts could not be opened.") { override suspend fun refreshRead() { repository.refreshMoney(moneyToday(clock, zone)) } } class MoneyAccountVisit internal constructor( val id: String, private val repository: MoneyRepository, private val clock: Clock, private val zone: ZoneId, scope: CoroutineScope, ) : MoneyReadVisit( id, scope, repository.accounts.map { it[id.trim()] ?: MoneyReadState.Loading }, MoneyReadState.Loading, "This account could not be opened.", ) { override suspend fun refreshRead() { repository.refreshAccount(id.trim(), moneyToday(clock, zone)) } } class MoneyStatementVisit internal constructor( val id: String, private val repository: MoneyRepository, scope: CoroutineScope, ) : MoneyReadVisit( id, scope, repository.statements.map { it[id.trim()] ?: MoneyReadState.Loading }, MoneyReadState.Loading, "This statement could not be opened.", ) { override suspend fun refreshRead() { repository.refreshStatement(id.trim()) } } class MoneyTransactionVisit internal constructor( val id: String, private val repository: MoneyRepository, scope: CoroutineScope, ) : MoneyReadVisit( id, scope, repository.transactions.map { it[id.trim()] ?: MoneyReadState.Loading }, MoneyReadState.Loading, "This transaction could not be opened.", ) { override suspend fun refreshRead() { repository.refreshTransaction(id.trim()) } }