package eu.friedcutlet.yokan.ui.screens.migration import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.data.observe import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.domain.Source import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory import eu.friedcutlet.yokan.services.extensions.RemoteDetail import eu.friedcutlet.yokan.services.extensions.RemoteManga import eu.friedcutlet.yokan.services.extensions.SourceListing import eu.friedcutlet.yokan.services.extensions.withSourceRuntime import eu.friedcutlet.yokan.services.migration.MigrationService import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch /** The candidate the user tapped, with its destination detail. */ internal data class MigrationPreview( val source: Source, val candidate: RemoteManga, val detail: RemoteDetail? = null, val loading: Boolean = true, val error: String? = null, val migrating: Boolean = false, ) internal data class MigrationState( val manga: Manga?, val query: String, val submittedQuery: String, /** The installed sources the submitted query ran on. */ val sources: List = emptyList(), val listings: Map = emptyMap(), val loadingSourceIds: Set = emptySet(), /** Lower-cased names of favorite titles of the title's type, for the "already in library" badge. */ val libraryTitleNames: Set = emptySet(), val preview: MigrationPreview? = null, ) /** Searches every installed source for [mangaId]'s replacement and migrates it to the chosen candidate. */ internal class MigrationViewModel( mangaId: Long, private val repository: YokanRepository, private val database: YokanDatabase, private val runtimeFactory: ExtensionRuntimeFactory, private val migration: MigrationService, ) : ViewModel() { private val _state = MutableStateFlow( repository.manga(mangaId).let { MigrationState(manga = it, query = it?.name.orEmpty(), submittedQuery = it?.name.orEmpty()) }, ) val state: StateFlow = _state.asStateFlow() private var searchJob: Job? = null private var previewJob: Job? = null init { _state.value.manga?.let { manga -> viewModelScope.launch { repository.observe({ it.mangas }) { allTitles(manga.itemType).filter { it.favorite }.mapTo(HashSet()) { it.name.lowercase() } }.collect { names -> _state.update { it.copy(libraryTitleNames = names) } } } search() } } fun changeQuery(query: String) { _state.update { it.copy(query = query) } } fun submit() { val state = _state.value if (state.query == state.submittedQuery) return _state.update { it.copy(submittedQuery = state.query) } search() } fun clear() { searchJob?.cancel() _state.update { it.copy(query = "", submittedQuery = "", listings = emptyMap(), loadingSourceIds = emptySet()) } } fun openPreview(source: Source, candidate: RemoteManga) { previewJob?.cancel() _state.update { it.copy(preview = MigrationPreview(source, candidate)) } previewJob = viewModelScope.launch { catchingNonCancellation { runtimeFactory.withSourceRuntime(database, source.id) { it.detail(candidate.url) } }.fold( onSuccess = { detail -> updatePreview { it.copy(detail = detail, loading = false) } }, onFailure = { error -> val message = error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() } updatePreview { it.copy(error = message, loading = false) } }, ) } } /** Also cancels a migration in flight, as closing the sheet always did. */ fun dismissPreview() { previewJob?.cancel() _state.update { it.copy(preview = null) } } /** Migrates to the previewed candidate; [onMigrated] runs once the new title exists. */ fun migrate(onMigrated: () -> Unit) { val state = _state.value val manga = state.manga ?: return val preview = state.preview ?: return if (preview.migrating) return updatePreview { it.copy(migrating = true) } previewJob = viewModelScope.launch { val newId = migration.migrate(manga, preview.source, preview.candidate) updatePreview { it.copy(migrating = false) } if (newId != null) { _state.update { it.copy(preview = null) } onMigrated() } } } private fun search() { searchJob?.cancel() val state = _state.value val manga = state.manga ?: return val query = state.submittedQuery if (query.isBlank()) return val sources = repository.sources(manga.itemType).filter { it.isActive && it.isAdded } _state.update { it.copy(sources = sources, listings = emptyMap(), loadingSourceIds = sources.mapTo(HashSet()) { source -> source.id }) } searchJob = viewModelScope.launch { sources.forEach { source -> launch { val listing = catchingNonCancellation { runtimeFactory.withSourceRuntime(database, source.id) { it.search(query, 1, emptyList()) } }.getOrNull() _state.update { it.copy(listings = it.listings + (source.id to listing), loadingSourceIds = it.loadingSourceIds - source.id) } } } } } private fun updatePreview(transform: (MigrationPreview) -> MigrationPreview) { _state.update { state -> state.preview?.let { state.copy(preview = transform(it)) } ?: state } } }