git.iko.soy/opencode-android
on 0bc1eda help sign in
79 lines 2.7 kB history raw
1package soy.iko.opencode.ui.server
3import androidx.lifecycle.ViewModel
4import androidx.lifecycle.viewModelScope
5import soy.iko.opencode.data.model.ServerProfile
6import soy.iko.opencode.di.AppContainer
7import kotlinx.coroutines.flow.MutableStateFlow
8import kotlinx.coroutines.flow.StateFlow
9import kotlinx.coroutines.flow.asStateFlow
10import kotlinx.coroutines.flow.first
11import kotlinx.coroutines.launch
12import java.util.UUID
14data class ServerEditState(
15 val id: String? = null,
16 val label: String = "",
17 val baseUrl: String = "",
18 val username: String = "",
19 val password: String = "",
20 val loaded: Boolean = false,
21) {
22 val canSave: Boolean get() = baseUrl.isNotBlank()
23 val isNew: Boolean get() = id == null
26class ServerEditViewModel(
27 private val container: AppContainer,
28 private val profileId: String?,
29) : ViewModel() {
31 private val _state = MutableStateFlow(ServerEditState(id = profileId))
32 val state: StateFlow<ServerEditState> = _state.asStateFlow()
34 init {
35 viewModelScope.launch {
36 if (profileId != null) {
37 val existing = container.profileStore.profiles.first().firstOrNull { it.id == profileId }
38 if (existing != null) {
39 _state.value = ServerEditState(
40 id = existing.id,
41 label = existing.label,
42 baseUrl = existing.baseUrl,
43 username = existing.username.orEmpty(),
44 password = existing.password.orEmpty(),
45 loaded = true,
46 )
47 return@launch
48 }
49 }
50 _state.value = _state.value.copy(loaded = true)
51 }
52 }
54 fun update(transform: (ServerEditState) -> ServerEditState) {
55 _state.value = transform(_state.value)
56 }
58 fun save(onDone: () -> Unit) {
59 val s = _state.value
60 if (!s.canSave) return
61 viewModelScope.launch {
62 val existingLastUsed = if (s.id != null) {
63 container.profileStore.profiles.first()
64 .firstOrNull { it.id == s.id }?.lastUsed ?: 0L
65 } else 0L
66 container.profileStore.save(
67 ServerProfile(
68 id = s.id ?: UUID.randomUUID().toString(),
69 label = s.label.trim(),
70 baseUrl = s.baseUrl.trim(),
71 username = s.username.trim().takeIf { it.isNotBlank() },
72 password = s.password.trim().takeIf { it.isNotEmpty() },
73 lastUsed = existingLastUsed,
74 ),
75 )
76 onDone()
77 }
78 }