package eu.friedcutlet.yokan.ui.screens.library import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import eu.friedcutlet.yokan.data.LibraryIndex import eu.friedcutlet.yokan.data.LibraryIndexStore import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.data.observeSnapshot import eu.friedcutlet.yokan.data.toDb import eu.friedcutlet.yokan.data.toDomain import eu.friedcutlet.yokan.data.toDomainMangas import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.services.download.ChapterDownloads import eu.friedcutlet.yokan.services.library.LibraryUpdateController import eu.friedcutlet.yokan.services.library.LibraryAiringService import kotlinx.coroutines.CancellationException import eu.friedcutlet.yokan.services.library.LocalLibraryController import eu.friedcutlet.yokan.ui.navigation.LibraryRequest import eu.friedcutlet.yokan.services.library.sortedChapters import kotlinx.coroutines.Job import kotlinx.coroutines.delay import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.database.DbLibraryGrouping import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * One item type's library: filtered and sorted entries per category, badges, the category and * selection cursor, and the library update. Lives in the root ViewModel store for the whole app. */ class LibraryViewModel( private val itemType: ItemType, private val repository: YokanRepository, private val settings: SettingsStore, private val libraryIndex: LibraryIndexStore, private val libraryUpdates: LibraryUpdateController, private val localLibrary: LocalLibraryController, private val chapterDownloads: ChapterDownloads, libraryRequests: Flow, private val airings: LibraryAiringService? = null, trackerProviders: List = emptyList(), private val workDispatcher: CoroutineDispatcher = Dispatchers.Default, ) : ViewModel() { private val _state = MutableStateFlow( LibraryState( itemType = itemType, query = settings.db.value.libraryQuery(itemType), display = settings.db.value.libraryDisplay(itemType), selectedCategoryId = defaultCategoryId(), trackerProviders = trackerProviders, ), ) val state: StateFlow = _state.asStateFlow() private var searchJob: Job? = null private var pendingSearch: String? = null init { val entries = repository.observeSnapshot({ it.mangas to it.settings.titleMetadata }, workDispatcher) { snapshot -> snapshot.mangas.filter { it.itemType == itemType.toDb() && it.favorite && it.parentId == null }.toDomainMangas(snapshot.settings) } .stateIn(viewModelScope, SharingStarted.Eagerly, null) .filterNotNull() // Empty is the placeholder before the first build; filtering against it would flash wrong results. val index = libraryIndex.index.filter { it !== LibraryIndex.Empty } viewModelScope.launch { settings.db.collect { db -> _state.update { it.copy(query = db.libraryQuery(itemType).let { query -> pendingSearch?.let { query.copy(search = it) } ?: query }, display = db.libraryDisplay(itemType)) } } } viewModelScope.launch { val releases = LibraryReleaseSelector() combine( entries, repository.observeSnapshot({ it.categories }, workDispatcher) { snapshot -> snapshot.categories.filter { it.forItemType == itemType.toDb() } .sortedBy { it.position ?: 0 }.map { it.toDomain() } }, index, settings.db.map { it.libraryQuery(itemType) }.distinctUntilChanged(), ) { titles, categories, built, query -> libraryContent(titles, categories, built, query, releases.select(titles, built, query)) } .flowOn(workDispatcher) .collect { content -> _state.update { it.withContent(content) } } } viewModelScope.launch { combine(entries, index, settings.db.map { db -> DbSettings(chapterReleasePreferences = db.chapterReleasePreferences, filterScanlatorList = db.filterScanlatorList, downloadedOnlyMode = db.downloadedOnlyMode) }.distinctUntilChanged()) { titles, built, db -> buildLibraryBadgeSummaries( chaptersByManga = titles.associate { it.id to built.chapters(it.id) }, completedDownloadCountsByChapterId = built.completedDownloadCountsByChapterId, mangaTitles = titles.associate { it.id to it.name }, releaseSettings = db, ) }.flowOn(workDispatcher).collect { badges -> _state.update { it.copy(badges = badges) } } } viewModelScope.launch { libraryRequests.filterNotNull().filter { it.itemType == itemType }.collect { applyRequest(it) } } } fun onEvent(event: LibraryEvent) { when (event) { LibraryEvent.Refresh -> refresh() LibraryEvent.RefreshAirings -> refreshAirings() is LibraryEvent.Search -> search(event.query) is LibraryEvent.SelectCategory -> _state.update { it.copy(selectedCategoryId = event.categoryId) } is LibraryEvent.UpdateSettings -> settings.updateDb(event.transform) is LibraryEvent.BeginSelection -> _state.update { if (it.selectionMode) it.withToggled(event.mangaId) else it.copy(selectedIds = setOf(event.mangaId)) } is LibraryEvent.ToggleSelection -> _state.update { it.withToggled(event.mangaId) } LibraryEvent.ClearSelection -> _state.update { it.copy(selectedIds = emptySet()) } LibraryEvent.SelectAll -> _state.update { state -> state.copy(selectedIds = state.currentItems.mapTo(HashSet()) { it.id }) } LibraryEvent.InvertSelection -> _state.update { state -> val visible = state.currentItems.mapTo(HashSet()) { it.id } state.copy(selectedIds = (state.selectedIds - visible) + (visible - state.selectedIds)) } is LibraryEvent.MarkSelectedRead -> writeSelection { ids -> repository.setLibraryEntriesRead(ids, event.isRead) } is LibraryEvent.SetSelectedCategories -> writeSelection { ids -> ids.forEach { repository.setMangaCategories(it, event.categoryIds) } } is LibraryEvent.RemoveSelected -> writeSelection { ids -> val removable = if (event.downloads) chapterDownloads.deleteForMangaAwait(ids) else ids if (event.fromLibrary) repository.removeLibraryEntries(removable) } LibraryEvent.RescanLocalLibrary -> viewModelScope.launch { localLibrary.rescan() } is LibraryEvent.ImportTorrent -> viewModelScope.launch { localLibrary.importTorrent(event.pathOrMagnet) } } } /** * Moves one visible category forward or back, wrapping at the ends. False when there are fewer * than two visible categories, so the caller can switch item types instead. */ fun shiftCategory(delta: Int): Boolean { val visible = listOf(null) + _state.value.content?.tabs.orEmpty().map { it.id } if (visible.size < 2) return false val current = visible.indexOf(_state.value.selectedCategoryId).takeIf { it >= 0 } ?: 0 val next = ((current + delta) % visible.size + visible.size) % visible.size _state.update { it.copy(selectedCategoryId = visible[next]) } return true } /** The chapter "continue" opens: the first unread one in the title's sort order, else the first. */ fun continueChapterId(manga: Manga): Long? { val chapters = sortedChapters(manga, libraryIndex.index.value.chapters(manga.id), settings.db.value) return (chapters.firstOrNull { !it.isRead } ?: chapters.firstOrNull())?.id } /** A query shows every category; otherwise the library opens on its default category. */ private fun applyRequest(request: LibraryRequest) { val query = request.query if (query != null) { searchJob?.cancel(); pendingSearch = null } if (query != null) settings.updateDb { it.withLibrarySearch(itemType, query) } _state.update { it.copy( selectedCategoryId = if (query != null) null else defaultCategoryId(), selectedIds = emptySet(), ) } } /** The first visible category, so the library opens on one category rather than all of them. */ private fun defaultCategoryId(): Long? = if (settings.db.value.features.library.grouping(itemType.toDb()) == DbLibraryGrouping.Categories) repository.categories(itemType).firstOrNull { !it.hidden }?.id else null /** Clears the selection, then runs [write] with its ids off the main thread. */ private fun writeSelection(write: suspend (Set) -> Unit) { val ids = _state.value.selectedIds _state.update { it.copy(selectedIds = emptySet()) } if (ids.isEmpty()) return viewModelScope.launch { withContext(workDispatcher) { write(ids) } } } private fun search(query: String) { searchJob?.cancel() pendingSearch = query _state.update { it.copy(query = it.query.copy(search = query)) } searchJob = viewModelScope.launch { delay(250) pendingSearch = null settings.updateDb { it.withLibrarySearch(itemType, query) } } } private fun refresh() { if (_state.value.refreshing) return val current = _state.value val titleIds = libraryUpdateTitleIds(current.content, current.selectedCategoryId, settings.db.value.features.library.updateGroupMode(itemType.toDb()), libraryIndex.index.value) _state.update { it.copy(refreshing = true, lastRefreshSummary = null) } viewModelScope.launch { try { val result = libraryUpdates.run(itemType, titleIds) val summary = "Checked ${result.checked}, updated ${result.updated}, failed ${result.failed}" _state.update { it.copy(lastRefreshSummary = summary) } } finally { _state.update { it.copy(refreshing = false) } } } } private fun refreshAirings() { if (itemType != ItemType.Anime || _state.value.refreshingAirings) return val service = airings ?: return _state.update { it.copy(refreshingAirings = true, airingRefreshResult = null, airingRefreshFailed = false) } viewModelScope.launch { try { val result = withContext(workDispatcher) { service.refresh() } _state.update { it.copy(airingRefreshResult = result) } } catch (cancel: CancellationException) { throw cancel } catch (_: Exception) { _state.update { it.copy(airingRefreshFailed = true) } } finally { _state.update { it.copy(refreshingAirings = false) } } } } } private fun LibraryState.withToggled(mangaId: Long): LibraryState = copy(selectedIds = if (mangaId in selectedIds) selectedIds - mangaId else selectedIds + mangaId) /** Publishes [content]; a deleted category falls back to all categories and removed titles leave the selection. */ private fun LibraryState.withContent(content: LibraryContent): LibraryState { val groupingChanged = (this.content?.grouping ?: DbLibraryGrouping.Categories) != content.grouping val categoryGone = selectedCategoryId != null && !content.containsCategory(selectedCategoryId) val libraryIds: Set = if (selectedIds.isEmpty()) emptySet() else content.library.mapTo(HashSet()) { it.id } val keptIds = if (selectedIds.all(libraryIds::contains)) selectedIds else selectedIds.filterTo(HashSet(), libraryIds::contains) return copy( content = content, selectedCategoryId = when { groupingChanged -> content.tabs.firstOrNull()?.id categoryGone -> null else -> selectedCategoryId }, selectedIds = keptIds, ) }