package com.peachpasswords.ui.lock import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.peachpasswords.vault.CreateVaultResult import com.peachpasswords.vault.UnlockResult import com.peachpasswords.vault.VaultRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject data class LockUiState( val hasVault: Boolean = false, val loading: Boolean = false, val error: String? = null, val unlocked: Boolean = false, /** Increments on each failed unlock so the screen can fire its shake animation. */ val shakeNonce: Int = 0, ) const val MIN_PASSWORD_LENGTH = 12 @HiltViewModel class LockViewModel @Inject constructor( private val vault: VaultRepository, ) : ViewModel() { private val _state = MutableStateFlow(LockUiState(hasVault = vault.hasVault())) val state: StateFlow = _state.asStateFlow() fun unlock(password: String) { if (password.isBlank() || _state.value.loading) return _state.update { it.copy(loading = true, error = null) } viewModelScope.launch { when (val r = vault.unlock(password)) { is UnlockResult.Success -> _state.update { it.copy(loading = false, unlocked = true) } is UnlockResult.WrongPassword -> _state.update { it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1) } is UnlockResult.Error -> _state.update { it.copy(loading = false, error = r.reason, shakeNonce = it.shakeNonce + 1) } } } } fun create(password: String, confirm: String) { if (_state.value.loading) return when { password.length < MIN_PASSWORD_LENGTH -> return _state.update { it.copy(error = "password must be at least $MIN_PASSWORD_LENGTH characters") } password != confirm -> return _state.update { it.copy(error = "passwords do not match") } } _state.update { it.copy(loading = true, error = null) } viewModelScope.launch { when (val r = vault.createVault(password)) { is CreateVaultResult.Success -> _state.update { it.copy(loading = false, unlocked = true) } is CreateVaultResult.Error -> _state.update { it.copy(loading = false, error = r.reason) } } } } fun clearError() = _state.update { it.copy(error = null) } /** Dormant until biometric enrollment lands with Protection settings. */ fun canTryBiometric(): Boolean = false }