package com.cottondb.android import com.cottondb.android.core.CottonCalling import com.cottondb.android.navigation.Route import com.cottondb.android.work.reader.ReaderDetailModel import com.cottondb.android.work.reader.ReaderListModel import com.cottondb.android.work.reader.ReaderRepository import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow /** Route visits own their writes, first-open stamps, and observed web address across rotation. */ class ReaderModels(core: CottonCalling, private val scope: CoroutineScope) { private val repository = ReaderRepository(core) private var list: ReaderListModel? = null private val pages = mutableMapOf() fun list(): ReaderListModel = list ?: ReaderListModel(repository, scope).also { list = it } fun page(id: String): ReaderPageVisit = pages.getOrPut(id) { ReaderPageVisit(ReaderDetailModel(id, repository, scope)) } fun retain(routes: List) { if (Route.Reader !in routes) { list?.close(); list = null } val ids = routes.filterIsInstance().map { it.id }.toSet() pages.keys.filterNot(ids::contains).forEach { pages.remove(it)?.model?.close() } } } data class ReaderWebState(val liveAddress: String? = null, val failure: String? = null, val attempt: Long = 0) class ReaderPageVisit(val model: ReaderDetailModel) { private val mutableWeb = MutableStateFlow(ReaderWebState()) val web = mutableWeb.asStateFlow() fun navigated(address: String, title: String?) { mutableWeb.value = mutableWeb.value.copy(liveAddress = address, failure = null) model.learnTitleIfNeeded(title) } fun failed(reason: String) { mutableWeb.value = mutableWeb.value.copy(failure = reason) } fun retryWeb() { mutableWeb.value = mutableWeb.value.copy(failure = null, attempt = mutableWeb.value.attempt + 1) } }