package eu.friedcutlet.yokan.ui.screens.browse import eu.friedcutlet.yokan.services.extensions.SourceListing import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.domain.Source import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.extensions.RemoteManga import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay 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 SourceSearchState( val loading: Boolean = false, val results: List = emptyList(), val error: String? = null, ) internal data class GlobalSearchUiState( val query: String = "", val submittedQuery: String = "", /** Installed, active sources of the item type, narrowed by the pinned-only and NSFW settings. */ val sources: List = emptyList(), val results: Map = emptyMap(), ) /** Searches every eligible source of [itemType] one after another for the submitted query. */ internal class GlobalSearchViewModel( private val itemType: ItemType, initialQuery: String, private val repository: YokanRepository, settings: SettingsStore, private val searchSource: suspend (Source, String) -> RuntimeLoad, private val workDispatcher: CoroutineDispatcher = Dispatchers.Default, ) : ViewModel() { private val _state = MutableStateFlow(GlobalSearchUiState(query = initialQuery, submittedQuery = initialQuery.trim())) val state: StateFlow = _state.asStateFlow() init { viewModelScope.launch { // Only these settings re-pick the sources; source rows changing mid-search do not restart it. settings.db.map { it.onlyIncludePinnedSources to it.showNsfw } .distinctUntilChanged() .collect { (pinnedOnly, showNsfw) -> val sources = repository.sources(itemType) .filter { it.isActive && it.isAdded } .filter { !pinnedOnly || it.isPinned } .filter { showNsfw || !it.isNsfw } _state.update { it.copy(sources = sources) } } } viewModelScope.launch { _state.map { it.submittedQuery to it.sources } .distinctUntilChanged() .collectLatest { (query, sources) -> search(query, sources) } } } private suspend fun search(query: String, sources: List) { if (query.isBlank()) { _state.update { it.copy(results = emptyMap()) } return } delay(250) _state.update { it.copy(results = sources.associate { source -> source.id to SourceSearchState(loading = true) }) } sources.forEach { source -> val result = catchingNonCancellation { withContext(workDispatcher) { searchSource(source, query) } }.fold( onSuccess = { SourceSearchState(results = it.value.items, error = it.warning) }, onFailure = { SourceSearchState(error = it.message.orEmpty().ifBlank { it::class.simpleName.orEmpty() }) }, ) _state.update { it.copy(results = it.results + (source.id to result)) } } } fun setQuery(query: String) = _state.update { it.copy(query = query) } fun submit() = _state.update { it.copy(submittedQuery = it.query.trim()) } /** Caches [remote] as a browsed title and returns its id for the Detail route. */ fun cacheRemote(source: Source, remote: RemoteManga): Long = repository.upsertRemoteTitle(source, remote).id }