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.DbSavedSearch import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.database.presetIdentity import eu.friedcutlet.yokan.domain.Source import eu.friedcutlet.yokan.services.extensions.FilterSelection import eu.friedcutlet.yokan.services.extensions.RemoteManga import eu.friedcutlet.yokan.services.extensions.SourceFilter import eu.friedcutlet.yokan.services.extensions.SourceListing import eu.friedcutlet.yokan.services.extensions.webViewUserAgent import eu.friedcutlet.yokan.services.extensions.PresetIssue import eu.friedcutlet.yokan.services.extensions.PresetIssueReason import eu.friedcutlet.yokan.services.extensions.PresetValidation import eu.friedcutlet.yokan.services.extensions.validateSourcePreset import eu.friedcutlet.yokan.services.catchingNonCancellation import kotlinx.coroutines.Job import eu.friedcutlet.yokan.ui.navigation.Route import eu.friedcutlet.yokan.util.PlatformLock import kotlinx.coroutines.CancellationException 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.collectLatest import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext internal data class SourceHomeLoadKey( val sourceId: Long, val tab: SourceTab, val query: String, val filterSelections: Map, val filtersApplied: Boolean, val revision: Long, ) internal data class SourceHomeUiState( val source: Source?, val genre: String? = null, // Match the Flutter source-home modes: Popular (0), Latest (1), Filter/Search (2). val selectedTab: SourceTab = SourceTab.Popular, val supportsLatest: Boolean = false, val isSearchMode: Boolean = false, val searchQuery: String = "", val submittedQuery: String = "", val filters: List = emptyList(), val selectedFilterValues: Map = emptyMap(), val appliedFilterValues: Map = emptyMap(), val filtersApplied: Boolean = false, val items: List = emptyList(), val page: Int = 1, val hasNextPage: Boolean = false, val appendExhausted: Boolean = false, val loading: Boolean = false, val loadingMore: Boolean = false, val error: String? = null, val loadedKey: SourceHomeLoadKey? = null, /** False while a genre request waits for the source's filter schema. */ val filtersReady: Boolean = true, /** Links of favourited titles from this source (matched by source name and language). */ val libraryLinks: Set = emptySet(), val savedSearches: List = emptyList(), val filterSchemaReady: Boolean = false, val requestRevision: Long = 0, val presetEditor: PresetEditor? = null, val presetReview: PresetReview? = null, val reviewFiltersRequested: Boolean = false, /** "Hide entries already in library" for this source's media type ([DbBrowsePreferences]). */ val hideLibrary: Boolean = false, ) { internal val loadKey: SourceHomeLoadKey? get() = source?.let { SourceHomeLoadKey(it.id, selectedTab, submittedQuery, appliedFilterValues, filtersApplied, requestRevision) } /** [items] as shown: re-derived from the loaded pages, so toggling or library changes never refetch. */ val visibleItems: List by lazy { items.withoutLibrary(hideLibrary, libraryLinks) } } /** Drops listing entries whose url is a favourite of the same source (the "in library" badge key). */ internal fun List.withoutLibrary(hide: Boolean, libraryLinks: Set): List = if (hide && libraryLinks.isNotEmpty()) filterNot { it.url in libraryLinks } else this /** Bound on consecutive pages fetched automatically because every entry was hidden as in-library. */ internal const val MaxHiddenPageFills = 5 /** * Last listing of recently closed Source Homes, so re-opening a source after a pop restores it. * Written only from [SourceHomeViewModel.onCleared]; entries are immutable states. */ internal class SourceHomeCache(private val capacity: Int) { private val lock = PlatformLock() private val entries = LinkedHashMap>() fun get(sourceId: Long, genre: String?): SourceHomeUiState? = lock.withLock { entries[sourceId]?.takeIf { it.first == genre }?.second } fun put(sourceId: Long, genre: String?, state: SourceHomeUiState) = lock.withLock { entries.remove(sourceId) entries[sourceId] = genre to state while (entries.size > capacity) entries.remove(entries.keys.first()) } } /** * Listing, search and filter state of one Source Home entry. Opening marks the source as last used * and heals a missing payload through [healPayload]. */ internal class SourceHomeViewModel( private val sourceId: Long, genre: String?, private val repository: YokanRepository, private val settings: SettingsStore, healPayload: (sourceId: Long) -> Unit, private val cache: SourceHomeCache, private val loadListing: suspend (Source, SourceTab, String, Int, List) -> RuntimeLoad, private val loadFilters: suspend (Source) -> List, private val loadLatestSupport: suspend (Source) -> Boolean, private val workDispatcher: CoroutineDispatcher = Dispatchers.Default, ) : ViewModel() { private val genre = genre?.trim()?.takeIf(String::isNotEmpty) private val _state: MutableStateFlow val state: StateFlow private var appendJob: Job? = null private var presetApplyJob: Job? = null init { repository.markSourceUsed(sourceId) val source = repository.source(sourceId) val cached = cache.get(sourceId, this.genre) _state = MutableStateFlow( (cached?.copy(source = source) ?: SourceHomeUiState( source = source, genre = this.genre, supportsLatest = source?.supportLatest ?: false, filtersReady = this.genre == null, )).copy(hideLibrary = source != null && settings.db.value.features.browse.hidesLibrary(source.itemType)), ) state = _state.asStateFlow() if (source != null) { healPayload(sourceId) collectSourceData(source) viewModelScope.launch { initialize(source, restored = cached != null) } viewModelScope.launch { // Re-fetch page 1 whenever the mode, the submitted query, or applied filters change. _state.map { if (it.filtersReady) it.loadKey else null } .distinctUntilChanged() .collectLatest { key -> appendJob?.cancel() if (key == null || _state.value.loadedKey == key) return@collectLatest _state.update { it.copy(items = emptyList(), page = 1, hasNextPage = false, appendExhausted = false) } if (loadPage(targetPage = 1, append = false)) _state.update { if (it.loadKey == key) it.copy(loadedKey = key) else it } } } viewModelScope.launch { fillHiddenPages() } } } private fun collectSourceData(initial: Source) { viewModelScope.launch { repository.observe({ it.sources }, workDispatcher) { source(sourceId) }.collect { source -> _state.update { it.copy(source = source) } } } viewModelScope.launch { // Mirror Flutter's library overlay: match favourites by source name + lang. repository.observe({ it.mangas }, workDispatcher) { allTitles(initial.itemType).asSequence() .filter { it.favorite && it.source.equals(initial.name, ignoreCase = true) && it.lang.equals(initial.lang, ignoreCase = true) } .map { it.link } .toSet() }.collect { links -> _state.update { it.copy(libraryLinks = links) } } } viewModelScope.launch { settings.db.map { db -> db.savedSearches.orEmpty().filter { it.sourceId == sourceId } } .distinctUntilChanged() .collect { saved -> _state.update { it.copy(savedSearches = saved) } } } viewModelScope.launch { settings.db.map { it.features.browse.hidesLibrary(initial.itemType) } .distinctUntilChanged() .collect { hide -> _state.update { it.copy(hideLibrary = hide) } } } } /** * Loading is manual (Load more tile), so a page whose entries are all in the library would leave * an empty screen without that tile: fetch following pages until something shows, at most * [MaxHiddenPageFills] in a row. A failed fetch keeps [SourceHomeUiState.page], which stops the run. */ private suspend fun fillHiddenPages() { var filled = 0 var lastPage = 0 _state.collect { s -> if (!s.hideLibrary || s.items.isEmpty() || s.visibleItems.isNotEmpty()) { filled = 0 lastPage = 0 return@collect } if (s.loading || s.loadingMore || !s.hasNextPage || s.page == lastPage || filled >= MaxHiddenPageFills) return@collect filled++ lastPage = s.page loadMore() } } private suspend fun initialize(source: Source, restored: Boolean) { val latest = withContext(workDispatcher) { loadLatestSupport(source) } _state.update { it.copy( supportsLatest = latest, selectedTab = if (!latest && it.selectedTab == SourceTab.Latest) SourceTab.Popular else it.selectedTab, ) } val fetched = catchingNonCancellation { withContext(workDispatcher) { loadFilters(source) } } val filters = fetched.getOrDefault(emptyList()) _state.update { current -> val withFilters = current.copy(filters = filters, filtersReady = true, filterSchemaReady = fetched.isSuccess) // A restored home keeps its own search instead of re-running the genre request. if (genre == null || restored) return@update withFilters val request = genreSearchRequest(genre, filters) withFilters.copy( selectedFilterValues = request.selections, appliedFilterValues = request.selections, submittedQuery = request.query, searchQuery = request.query, selectedTab = SourceTab.Search, filtersApplied = request.selections.isNotEmpty(), isSearchMode = request.query.isNotEmpty(), ) } } private suspend fun loadPage(targetPage: Int, append: Boolean): Boolean { val current = _state.value val source = current.source ?: return false if (append && (current.loadingMore || current.loading)) return false _state.update { if (append) it.copy(loadingMore = true, error = null) else it.copy(loading = true, error = null) } return try { // Applied schema = schema with the user's selections folded in; the runtime receives it. val appliedFilters = current.filters.map { it.copy(selection = current.appliedFilterValues[it.id]) } val load = withContext(workDispatcher) { loadListing(source, current.selectedTab, current.submittedQuery, targetPage, appliedFilters) } _state.update { s -> if (s.loadKey != current.loadKey) return@update s val combined = if (append) s.items + load.value.items else load.value.items val seen = HashSet(combined.size) val items = combined.filter { seen.add(it.url) } s.copy( items = items, page = targetPage, hasNextPage = load.value.hasNextPage, appendExhausted = append && items.size == s.items.size && !load.value.hasNextPage, error = load.warning, ) } true } catch (throwable: Throwable) { if (throwable is CancellationException) throw throwable val message = throwable.message.orEmpty().ifBlank { throwable::class.simpleName.orEmpty() } _state.update { if (it.loadKey == current.loadKey) it.copy(items = if (append) it.items else emptyList(), error = message) else it } false } finally { _state.update { if (it.loadKey == current.loadKey) it.copy(loading = false, loadingMore = false) else it } } } fun retry() { viewModelScope.launch { loadPage(1, append = false) } } fun loadMore() { val current = _state.value if (!current.loadingMore && (current.hasNextPage || current.selectedTab != SourceTab.Popular)) { appendJob = viewModelScope.launch { loadPage(current.page + 1, append = true) } } } /** Per media type, shared with Home source feeds; the settings collector re-filters loaded pages. */ fun setHideLibrary(hide: Boolean) { val type = _state.value.source?.itemType ?: return settings.updateDb { it.copy(features = it.features.copy(browse = it.features.browse.withHideLibrary(type, hide))) } } fun setSearchQuery(query: String) = _state.update { it.copy(searchQuery = query) } fun enterSearchMode() = _state.update { it.copy(isSearchMode = true, searchQuery = it.submittedQuery) } fun submitSearch() = _state.update { val trimmed = it.searchQuery.trim() if (trimmed.isEmpty()) { it.copy(selectedTab = SourceTab.Popular, submittedQuery = "") } else { it.copy(selectedTab = SourceTab.Search, submittedQuery = trimmed) } } /** Clears the query; a running search falls back to Popular. */ fun clearSearch() = _state.update { it.clearedSearch() } /** Back arrow or Escape inside search mode: first clear the text, then leave search mode. */ fun backFromSearch() = _state.update { if (it.searchQuery.isBlank()) { it.copy( isSearchMode = false, submittedQuery = "", selectedTab = if (it.selectedTab == SourceTab.Search) SourceTab.Popular else it.selectedTab, ) } else { it.copy(searchQuery = "") } } /** Popular / Latest chips. */ fun selectListing(tab: SourceTab) = _state.update { it.copy(selectedTab = tab, submittedQuery = "", searchQuery = "", isSearchMode = false) } fun setFilterSelection(filterId: String, selection: FilterSelection?) = _state.update { it.copy( selectedFilterValues = if (selection == null) { it.selectedFilterValues - filterId } else { it.selectedFilterValues + (filterId to selection) }, ) } fun resetFilters() { _state.update { it.copy(selectedFilterValues = emptyMap()) } val source = _state.value.source ?: return viewModelScope.launch { catchingNonCancellation { withContext(workDispatcher) { loadFilters(source) } } .onSuccess { filters -> _state.update { it.copy(filters = filters, filterSchemaReady = true) } } .onFailure { failure -> _state.update { it.copy(filterSchemaReady = false, error = failure.message) } } } } fun applyFilters() = _state.update { it.copy(appliedFilterValues = it.selectedFilterValues, submittedQuery = it.searchQuery.trim(), selectedTab = SourceTab.Search, filtersApplied = !it.filtersApplied, reviewFiltersRequested = false) } private fun savedPreset(id: String): DbSavedSearch? = settings.db.value.sourcePreset(sourceId, id) private fun sourceRow(): DbSource? = repository.snapshots.value.sources.firstOrNull { it.id == sourceId } fun onPresetEvent(event: SourcePresetEvent) { val current = _state.value when (event) { SourcePresetEvent.SaveCurrent -> if (current.filterSchemaReady) _state.update { it.copy(presetEditor = PresetEditor(PresetEditMode.Save, it.searchQuery.trim())) } is SourcePresetEvent.Rename -> savedPreset(event.id)?.let { saved -> _state.update { it.copy(presetEditor = PresetEditor(PresetEditMode.Rename, saved.name, saved.id)) } } is SourcePresetEvent.Update -> if (current.filterSchemaReady) savedPreset(event.id)?.let { saved -> _state.update { it.copy(presetEditor = PresetEditor(PresetEditMode.Update, saved.name, saved.id)) } } is SourcePresetEvent.NameChanged -> _state.update { it.copy(presetEditor = it.presetEditor?.copy( name = event.name, conflictId = null, invalidName = false)) } is SourcePresetEvent.Commit -> commitPresetEdit(event.replace) SourcePresetEvent.CancelEdit -> _state.update { it.copy(presetEditor = null) } is SourcePresetEvent.Apply -> { presetApplyJob?.cancel() presetApplyJob = viewModelScope.launch { val saved = savedPreset(event.id) ?: return@launch val source = _state.value.source ?: return@launch if (saved.sourceIdentity != null && sourceRow()?.presetIdentity() != saved.sourceIdentity) { applyPreset(saved) return@launch } val fetched = catchingNonCancellation { withContext(workDispatcher) { loadFilters(source) } } fetched.onSuccess { filters -> _state.update { it.copy(filters = filters, filterSchemaReady = true) } // Read the current stored row again in case it was deleted or renamed during fetch. savedPreset(event.id)?.let(::applyPreset) }.onFailure { _state.update { it.copy(presetReview = PresetReview(saved, PresetValidation(emptyMap(), listOf(PresetIssue(saved.name, PresetIssueReason.SchemaUnavailable))))) } } } } is SourcePresetEvent.Delete -> settings.updateDb { it.withoutSourcePreset(sourceId, event.id) } SourcePresetEvent.CancelReview -> _state.update { it.copy(presetReview = null) } SourcePresetEvent.CloseReviewFilters -> _state.update { it.copy(reviewFiltersRequested = false) } SourcePresetEvent.ReviewFilters -> { val saved = current.presetReview?.preset ?: return val source = sourceRow() ?: return val checked = validateSourcePreset(saved, source, current.filters) if (!current.filterSchemaReady || !checked.canReview) return // Only stage the recoverable combination. No request runs until Filter is pressed. _state.update { it.copy(presetReview = null, searchQuery = saved.query, isSearchMode = true, selectedFilterValues = checked.selections, reviewFiltersRequested = true) } } } } private fun commitPresetEdit(replace: Boolean) { val source = sourceRow() ?: return val commit = commitPreset(_state.value, settings.db.value, source, replace) ?: return commit.save?.let { preset -> settings.updateDb { it.withSourcePreset(preset) } } _state.update { it.copy(presetEditor = commit.editor) } } private fun applyPreset(preset: DbSavedSearch) { val source = sourceRow() ?: return _state.update { it.withPresetApplied(preset, source) } } /** Caches [remote] as a browsed title and returns its id for the Detail route. */ fun cacheRemote(remote: RemoteManga): Long? = _state.value.source?.let { repository.upsertRemoteTitle(it, remote).id } fun webViewRoute(): Route.InAppWebView? { val source = _state.value.source?.takeIf { it.baseUrl.isNotBlank() } ?: return null val userAgent = settings.db.value.webViewUserAgent(source).takeIf { it.isNotBlank() } return Route.InAppWebView(source.baseUrl, source.name, userAgent) } override fun onCleared() { val current = _state.value // Do not restore an interrupted genre request as an already initialized home. if (current.filtersReady && current.source != null) { cache.put(sourceId, genre, current.copy(loading = false, loadingMore = false, presetEditor = null, presetReview = null, reviewFiltersRequested = false)) } } } private fun SourceHomeUiState.clearedSearch() = copy( searchQuery = "", submittedQuery = "", selectedTab = if (selectedTab == SourceTab.Search) SourceTab.Popular else selectedTab, )