82 lines
2.7 KiB
Kotlin
82 lines
2.7 KiB
Kotlin
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) }
|
||
}
|
||
}
|