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.domain.ItemType import eu.friedcutlet.yokan.domain.Source import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch internal data class MassMigrationSourceRow(val source: Source, val libraryCount: Int) /** Sources of [itemType] that have favorite titles; null until the library has been read. */ internal class MassMigrationSourceViewModel(itemType: ItemType, repository: YokanRepository) : ViewModel() { private val _state = MutableStateFlow?>(null) val state: StateFlow?> = _state.asStateFlow() init { viewModelScope.launch { repository.observe({ it.mangas to it.sources }) { val counts = allTitles(itemType).filter { it.favorite }.groupingBy { it.source }.eachCount() sources(itemType).mapNotNull { source -> counts[source.name]?.let { MassMigrationSourceRow(source, it) } } }.collect { _state.value = it } } } }