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.Source import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch internal data class MassMigrationDestinationState( val source: Source?, /** Null until the sources have been read. */ val destinations: List? = null, val selectedIds: List = emptyList(), ) /** * Installed (`isAdded`) sources of the migrated source's type, excluding itself; migrating to an * uninstalled extension would just fail at the runtime step. */ internal class MassMigrationDestinationViewModel(sourceId: Long, repository: YokanRepository) : ViewModel() { private val _state = MutableStateFlow(MassMigrationDestinationState(source = repository.source(sourceId))) val state: StateFlow = _state.asStateFlow() init { _state.value.source?.let { source -> viewModelScope.launch { repository.observe({ it.sources }) { sources(source.itemType).filter { it.isActive && it.isAdded && it.id != source.id && (source.lang.isBlank() || it.lang.isBlank() || it.lang.equals("all", true) || it.lang.equals(source.lang, true)) } }.collect { destinations -> _state.update { it.copy(destinations = destinations, selectedIds = it.selectedIds.filter { id -> destinations.any { source -> source.id == id } }) } } } } } fun toggle(id: Long) = _state.update { state -> if (state.destinations.orEmpty().none { it.id == id }) state else state.copy( selectedIds = if (id in state.selectedIds) state.selectedIds - id else state.selectedIds + id, ) } fun move(id: Long, direction: Int) = _state.update { state -> val index = state.selectedIds.indexOf(id) val next = index + direction if (index < 0 || next !in state.selectedIds.indices) state else state.copy(selectedIds = state.selectedIds.toMutableList().apply { this[index] = this[next].also { this[next] = this[index] } }) } }