65 lines
1.9 KiB
Kotlin
65 lines
1.9 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()
|
|
}
|
|
|
|
private fun refreshState() {
|
|
_state.update {
|
|
it.copy(
|
|
baseUrl = serverConfig.getBaseUrl(),
|
|
config = serverConfig.getServerConfig()
|
|
)
|
|
}
|
|
}
|
|
|
|
fun loadConfig() {
|
|
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) {
|
|
serverConfig.setBaseUrl(url)
|
|
_state.update { it.copy(baseUrl = url) }
|
|
}
|
|
}
|