package eu.friedcutlet.yokan.ui.screens.migration import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import eu.friedcutlet.yokan.services.migration.* import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch internal data class MassMigrationRunnerState( val progress: MassMigrationProgress? = null, val busyWithAnotherRun: Boolean = false, ) /** Mirrors the run owned by this repository/session; route recreation does not restart it. */ internal class MassMigrationRunnerViewModel( sourceId: Long, destinationIds: List, mangaIds: List, private val migration: MigrationService, ) : ViewModel() { private val _state = MutableStateFlow(MassMigrationRunnerState()) val state = _state.asStateFlow() init { val accepted = migration.start(sourceId, destinationIds, mangaIds) _state.update { it.copy(busyWithAnotherRun = !accepted) } if (accepted) viewModelScope.launch { migration.progress.collect { progress -> if (progress?.sourceId == sourceId && progress.destinationIds == destinationIds.distinct() && progress.mangaIds == mangaIds.distinct()) { _state.update { it.copy(progress = progress) } } } } } fun select(id: Long, key: MigrationCandidateKey?) = migration.select(id, key) fun retry(id: Long) = migration.retry(id) fun commit() = migration.commitSelected() fun cancel() = migration.cancel() }