MassMigrationDestinationViewModel.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/migration/MassMigrationDestinationViewModel.kt
1package eu.friedcutlet.yokan.ui.screens.migration23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.data.YokanRepository6import eu.friedcutlet.yokan.data.observe7import eu.friedcutlet.yokan.domain.Source8import kotlinx.coroutines.flow.MutableStateFlow9import kotlinx.coroutines.flow.StateFlow10import kotlinx.coroutines.flow.asStateFlow11import kotlinx.coroutines.flow.update12import kotlinx.coroutines.launch1314internal data class MassMigrationDestinationState(15 val source: Source?,16 /** Null until the sources have been read. */17 val destinations: List<Source>? = null,18 val selectedIds: List<Long> = emptyList(),19)2021/**22 * Installed (`isAdded`) sources of the migrated source's type, excluding itself; migrating to an23 * uninstalled extension would just fail at the runtime step.24 */25internal class MassMigrationDestinationViewModel(sourceId: Long, repository: YokanRepository) : ViewModel() {26 private val _state = MutableStateFlow(MassMigrationDestinationState(source = repository.source(sourceId)))27 val state: StateFlow<MassMigrationDestinationState> = _state.asStateFlow()2829 init {30 _state.value.source?.let { source ->31 viewModelScope.launch {32 repository.observe({ it.sources }) {33 sources(source.itemType).filter { it.isActive && it.isAdded && it.id != source.id &&34 (source.lang.isBlank() || it.lang.isBlank() || it.lang.equals("all", true) || it.lang.equals(source.lang, true)) }35 }.collect { destinations -> _state.update { it.copy(destinations = destinations,36 selectedIds = it.selectedIds.filter { id -> destinations.any { source -> source.id == id } }) } }37 }38 }39 }4041 fun toggle(id: Long) = _state.update { state ->42 if (state.destinations.orEmpty().none { it.id == id }) state else state.copy(43 selectedIds = if (id in state.selectedIds) state.selectedIds - id else state.selectedIds + id,44 )45 }4647 fun move(id: Long, direction: Int) = _state.update { state ->48 val index = state.selectedIds.indexOf(id)49 val next = index + direction50 if (index < 0 || next !in state.selectedIds.indices) state else state.copy(selectedIds = state.selectedIds.toMutableList().apply {51 this[index] = this[next].also { this[next] = this[index] }52 })53 }54}55