package eu.friedcutlet.yokan.ui.screens.browse import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.data.observe import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.domain.Source import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.extensions.SourceInstallService import eu.friedcutlet.yokan.services.extensions.VersionComparison import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import eu.friedcutlet.yokan.services.extensions.languageName /** One item type's Browse panes, grouped off the main thread. */ internal data class BrowseSources( /** Added, active sources (NSFW-filtered); empty shows the "no sources" state. */ val visible: List = emptyList(), val lastUsed: List = emptyList(), val pinned: List = emptyList(), val byLanguage: List>> = emptyList(), /** Active extensions (NSFW-filtered, hidden repositories dropped) before the search query. */ val catalog: List = emptyList(), /** Active sources with a newer version, for the Extensions tab badge. */ val updateCount: Int = 0, ) internal data class BrowseUiState( val sources: Map = emptyMap(), val refreshing: Set = emptySet(), val refreshFailed: Set = emptySet(), val updatingAll: Set = emptySet(), /** Source ids with an install or update in flight. */ val installing: Set = emptySet(), val installFailed: Set = emptySet(), ) private fun needsUpdate(source: Source): Boolean = VersionComparison.isOutdated(source.version, source.versionLast) private fun sortedByLanguage(sources: List): List>> = sources .groupBy { languageName(it.lang.ifBlank { "other" }) } .toList() .sortedBy { (language, _) -> language } .map { (language, rows) -> language to rows.sortedBy { it.name.lowercase() } } /** Update, installed and per-language available sections of the extension catalogue matching [query]. */ internal fun extensionSections(catalog: List, query: String): ExtensionSections { val filtered = if (query.isBlank()) catalog else catalog.filter { it.name.contains(query, ignoreCase = true) } return ExtensionSections( isEmpty = filtered.isEmpty(), updates = filtered.filter(::needsUpdate).sortedBy { it.name.lowercase() }, installed = filtered.filter { it.isAdded && it.version == it.versionLast }.sortedBy { it.name.lowercase() }, availableByLanguage = sortedByLanguage(filtered.filter { !it.isAdded && it.version == it.versionLast }), ) } internal data class ExtensionSections( val isEmpty: Boolean, val updates: List, val installed: List, val availableByLanguage: List>>, ) private fun browseSources(type: ItemType, all: List, db: DbSettings): BrowseSources { val hiddenRepoUrls = when (type) { ItemType.Manga -> db.mangaExtensionsRepo ItemType.Anime -> db.animeExtensionsRepo ItemType.Novel -> db.novelExtensionsRepo }.orEmpty() .filter { it.hidden == true } .mapNotNull { it.jsonUrl?.trim() } .toSet() val visible = all.filter { it.isActive && it.isAdded && (db.showNsfw || !it.isNsfw) } return BrowseSources( visible = visible, lastUsed = visible.filter { it.lastUsed }.sortedBy { it.name.lowercase() }, pinned = visible.filter { it.isPinned }.sortedBy { it.name.lowercase() }, byLanguage = sortedByLanguage(visible.filterNot { it.isPinned }), catalog = all.filter { source -> source.isActive && (db.showNsfw || !source.isNsfw) && source.repo?.jsonUrl?.trim()?.let { it !in hiddenRepoUrls } != false }, updateCount = all.count { it.isActive && needsUpdate(it) }, ) } private fun allBrowseSources(all: Map>, db: DbSettings): Map = all.mapValues { (type, sources) -> browseSources(type, sources, db) } /** Browse root: installed sources and the extension catalogue for every item type. */ internal class BrowseViewModel( private val repository: YokanRepository, settings: SettingsStore, private val sourceInstall: SourceInstallService, private val workDispatcher: CoroutineDispatcher = Dispatchers.Default, ) : ViewModel() { // Seeded synchronously so the first frame never flashes "No sources installed". private val _state = MutableStateFlow( BrowseUiState(sources = allBrowseSources(ItemType.entries.associateWith(repository::sources), settings.db.value)), ) val state: StateFlow = _state.asStateFlow() init { viewModelScope.launch { combine( repository.observe({ it.sources }, workDispatcher) { ItemType.entries.associateWith { sources(it) } }, settings.db.distinctUntilChanged { old, new -> old.showNsfw == new.showNsfw && old.mangaExtensionsRepo == new.mangaExtensionsRepo && old.animeExtensionsRepo == new.animeExtensionsRepo && old.novelExtensionsRepo == new.novelExtensionsRepo }, ) { all, db -> allBrowseSources(all, db) } .flowOn(workDispatcher) .collect { sources -> _state.update { it.copy(sources = sources) } } } } fun togglePinned(source: Source) = repository.setSourcePinned(source.id, !source.isPinned) /** Re-reads every visible repository of [itemType]. */ fun refresh(itemType: ItemType) { if (itemType in _state.value.refreshing) return _state.update { it.copy(refreshing = it.refreshing + itemType, refreshFailed = it.refreshFailed - itemType) } viewModelScope.launch { val result = catchingNonCancellation { withContext(workDispatcher) { repository.repositories(itemType) .filter { it.hidden != true } .forEach { sourceInstall.refreshRepository(itemType, it) } } } _state.update { it.copy( refreshing = it.refreshing - itemType, refreshFailed = if (result.isFailure) it.refreshFailed + itemType else it.refreshFailed, ) } } } fun updateAll(itemType: ItemType, sourceIds: List) { viewModelScope.launch { _state.update { it.copy(updatingAll = it.updatingAll + itemType) } sourceIds.forEach { id -> catchingNonCancellation { sourceInstall.installOrUpdate(id) } } _state.update { it.copy(updatingAll = it.updatingAll - itemType) } } } fun install(sourceId: Long) { if (sourceId in _state.value.installing) return _state.update { it.copy(installing = it.installing + sourceId, installFailed = it.installFailed - sourceId) } viewModelScope.launch { val succeeded = catchingNonCancellation { sourceInstall.installOrUpdate(sourceId) }.getOrDefault(false) _state.update { it.copy( installing = it.installing - sourceId, installFailed = if (succeeded) it.installFailed else it.installFailed + sourceId, ) } } } fun uninstall(sourceId: Long) { sourceInstall.uninstall(sourceId) } }