Files
forkmessager/client-mobile/core/presentation/settings/SettingsViewModel.kt
2026-04-17 16:23:52 +03:00

82 lines
2.7 KiB
Kotlin
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package core.presentation.settings
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import core.domain.model.ServerConfigModel
import core.network.ServerConfig
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 SettingsState(
val baseUrl: String = "",
val config: ServerConfigModel = ServerConfigModel(),
val isLoading: Boolean = false,
val error: String? = null
)
@HiltViewModel
class SettingsViewModel @Inject constructor(
private val serverConfig: ServerConfig,
private val authRepository: auth.domain.repository.AuthRepository
) : ViewModel() {
private val _state = MutableStateFlow(SettingsState())
val state: StateFlow<SettingsState> = _state.asStateFlow()
init {
refreshState()
// loadConfig() убран - вызывается только по кнопке Refresh или если URL уже введён
}
private fun refreshState() {
_state.update {
it.copy(
baseUrl = serverConfig.getBaseUrl(),
config = serverConfig.getServerConfig()
)
}
}
fun loadConfig() {
// Не загружаем конфиг, если URL не введён
val currentUrl = serverConfig.getBaseUrl()
if (currentUrl.isBlank()) {
android.util.Log.d("SettingsViewModel", "Base URL is empty, skipping config load")
return
}
viewModelScope.launch {
_state.update { it.copy(isLoading = true, error = null) }
val result = authRepository.fetchConfig()
Log.d("SettingsViewModel", "Fetch result: ${result.isSuccess}")
if (result.isSuccess) {
refreshState()
} else {
_state.update { it.copy(error = result.exceptionOrNull()?.message) }
}
_state.update { it.copy(isLoading = false) }
}
}
fun saveBaseUrl(url: String) {
val currentUrl = serverConfig.getBaseUrl()
// Если URL действительно изменился, очищаем токен и логируем
if (currentUrl != url) {
android.util.Log.d("SettingsViewModel", "Server URL changed: $currentUrl -> $url, clearing token")
viewModelScope.launch {
authRepository.logout()
}
}
serverConfig.setBaseUrl(url)
_state.update { it.copy(baseUrl = url) }
}
}