Files
forkmessager/client-mobile/profiles/presentation/viewmodel/ProfileViewModel.kt
2026-04-16 15:41:22 +03:00

90 lines
3.6 KiB
Kotlin

package profiles.presentation.viewmodel
import android.net.Uri
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import profiles.data.remote.dto.ProfileDto
import profiles.domain.repository.ProfileRepository
import javax.inject.Inject
data class ProfileState(
val profile: ProfileDto? = null,
val isLoading: Boolean = false,
val error: String? = null,
val isSaving: Boolean = false
)
@HiltViewModel
class ProfileViewModel @Inject constructor(
private val repository: ProfileRepository
) : ViewModel() {
private val _state = MutableStateFlow(ProfileState())
val state: StateFlow<ProfileState> = _state.asStateFlow()
fun loadProfile(id: String? = null) {
viewModelScope.launch {
_state.value = _state.value.copy(isLoading = true)
val result = if (id == null) {
repository.getMyProfile()
} else {
repository.getProfile(id)
}
result.onSuccess { profile ->
_state.value = _state.value.copy(profile = profile, isLoading = false)
}.onFailure { error ->
_state.value = _state.value.copy(error = error.message, isLoading = false)
}
}
}
fun updateProfile(displayName: String?, bio: String?, birthday: String? = null, avatarUri: Uri? = null) {
viewModelScope.launch {
_state.value = _state.value.copy(isSaving = true, error = null)
try {
// 1. Обновляем аватар, если он выбран
avatarUri?.let { uri ->
repository.uploadAvatar(uri).onFailure { error ->
throw Exception(error.message ?: "Failed to upload avatar")
}
}
// 2. Обновляем текстовые данные
// Пустую строку преобразуем в null для даты рождения
val birthdayToSend = if (birthday.isNullOrBlank()) null else birthday
// Логирование для отладки
android.util.Log.d("ProfileViewModel", "updateProfile: displayName=$displayName, bio=$bio, birthday=$birthday, birthdayToSend=$birthdayToSend")
repository.updateProfile(displayName, bio, birthdayToSend)
.onSuccess { updatedProfile ->
android.util.Log.d("ProfileViewModel", "updateProfile success: birthday=${updatedProfile.birthday}")
_state.value = _state.value.copy(profile = updatedProfile, isSaving = false)
}
.onFailure { error ->
android.util.Log.e("ProfileViewModel", "updateProfile error: ${error.message}")
_state.value = _state.value.copy(error = error.message, isSaving = false)
}
} catch (e: Exception) {
android.util.Log.e("ProfileViewModel", "updateProfile exception: ${e.message}")
_state.value = _state.value.copy(error = e.message, isSaving = false)
}
}
}
fun removeAvatar() {
viewModelScope.launch {
repository.removeAvatar().onSuccess { updatedProfile ->
_state.value = _state.value.copy(profile = updatedProfile)
}
}
}
}