package eu.friedcutlet.yokan.ui.screens.local import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.library.LocalLibraryController import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch data class LocalLibraryBrowseUiState( /** Every local-archive title per type, sorted by name. */ val titlesByType: Map> = emptyMap(), val scanMessage: String? = null, val scanning: Boolean = false, ) class LocalLibraryBrowseViewModel( private val controller: LocalLibraryController, private val workDispatcher: CoroutineDispatcher = Dispatchers.Default, ) : ViewModel() { private val _state = MutableStateFlow(LocalLibraryBrowseUiState()) val state: StateFlow = _state.asStateFlow() init { viewModelScope.launch { controller.observeLibrary(workDispatcher).collect { library -> _state.update { it.copy(titlesByType = library.browseTitlesByType) } } } } fun rescan() { if (_state.value.scanning) return _state.update { it.copy(scanning = true) } viewModelScope.launch { val result = catchingNonCancellation { controller.rescan() } val message = result.fold( onSuccess = { "Last scan: ${it.total} items, ${it.added} added, ${it.updated} updated" }, onFailure = { error -> "Scan failed: ${error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() }}" }, ) _state.update { it.copy(scanMessage = message, scanning = false) } } } }