package eu.friedcutlet.yokan.ui.screens.extensions import androidx.lifecycle.ViewModel import eu.friedcutlet.yokan.data.toDomain import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.database.YokanDatabase 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 internal data class CreateExtensionUiState( val created: Source? = null, val error: String? = null, ) /** Saves a locally authored extension source. */ internal class CreateExtensionViewModel(private val database: YokanDatabase) : ViewModel() { private val _state = MutableStateFlow(CreateExtensionUiState()) val state: StateFlow = _state.asStateFlow() fun create(source: DbSource) { runCatching { database.upsertSource(source) } .onSuccess { saved -> _state.value = CreateExtensionUiState(created = saved.toDomain()) } .onFailure { err -> _state.update { it.copy(error = err.message ?: "Could not create extension") } } } }