package eu.friedcutlet.yokan.ui.screens.settings.player import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import eu.friedcutlet.yokan.data.CustomButtonRepository import eu.friedcutlet.yokan.database.DbCustomButton import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch /** Presentation state and commands; storage ordering/publication belongs to the repository. */ internal class CustomButtonsViewModel(private val repository: CustomButtonRepository) : ViewModel() { private val _buttons = MutableStateFlow(repository.snapshot()) val buttons: StateFlow> = _buttons.asStateFlow() init { viewModelScope.launch { repository.observeChanges().collect { reload() } } } fun save(button: DbCustomButton) = write { repository.save(button) } fun remove(buttonId: Long) = write { repository.remove(buttonId) } fun setFavourite(buttonId: Long) = write { repository.setFavourite(buttonId) } fun move(buttonId: Long, targetIndex: Int) = write { repository.move(buttonId, targetIndex) } // Preserve immediate drag feedback; never put a storage command inside retryable update(). private fun write(command: () -> Unit) { command() reload() } private fun reload() { val next = repository.snapshot() _buttons.update { next } } }