-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathMainViewModel.kt
More file actions
188 lines (168 loc) · 6.59 KB
/
MainViewModel.kt
File metadata and controls
188 lines (168 loc) · 6.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package com.greybox.projectmesh.mainscreen
import android.content.SharedPreferences
import android.os.Build
import android.os.Environment
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ustadmobile.meshrabiya.vnet.AndroidVirtualNode
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 org.kodein.di.DI
import org.kodein.di.instance
class MainViewModel(
di: DI
) : ViewModel() {
// Inject dependencies
private val settingPrefs: SharedPreferences by di.instance(tag = "settings")
private val meshPrefs: SharedPreferences by di.instance(tag = "mesh")
private val node: AndroidVirtualNode by di.instance()
// Private mutable state
private val _uiState = MutableStateFlow(MeshUiState())
// Public immutable state
val uiState: StateFlow<MeshUiState> = _uiState.asStateFlow()
init {
Log.d(TAG, "MainViewModel initialized")
loadInitialState()
observeMeshNetwork()
}
/**
* Load initial state from SharedPreferences
*/
private fun loadInitialState() {
viewModelScope.launch {
_uiState.update { state ->
state.copy(
deviceName = settingPrefs.getString("device_name", Build.MODEL) ?: Build.MODEL,
appTheme = settingPrefs.getString("app_theme", "SYSTEM") ?: "SYSTEM",
languageCode = settingPrefs.getString("language", "en") ?: "en",
autoFinish = settingPrefs.getBoolean("auto_finish", false),
saveToFolder = settingPrefs.getString("save_to_folder", null)
?: "${Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)}/Project Mesh",
hasRunBefore = meshPrefs.getBoolean("hasRunBefore", false)
)
}
}
}
/**
* Observe mesh network state changes
*/
private fun observeMeshNetwork() {
viewModelScope.launch {
node.state.collect { nodeState ->
_uiState.update { state ->
state.copy(
wifiState = nodeState.wifiState,
localAddress = nodeState.address,
nodesOnMesh = nodeState.originatorMessages.keys,
connectedNodesCount = nodeState.originatorMessages.size,
isNetworkActive = nodeState.wifiState.hotspotIsStarted,
statusMessage = if (nodeState.wifiState.hotspotIsStarted) {
"Mesh active - ${nodeState.originatorMessages.size} nodes"
} else {
"Mesh network inactive"
}
)
}
}
}
}
/**
* Handle UI events
*/
fun onEvent(event: MeshUiEvent) {
when (event) {
is MeshUiEvent.StartMeshNetwork -> startMeshNetwork()
is MeshUiEvent.StopMeshNetwork -> stopMeshNetwork()
is MeshUiEvent.NavigateToScreen -> navigateToScreen(event.route)
is MeshUiEvent.NavigateToChat -> navigateToChat(event.identifier)
is MeshUiEvent.UpdateDeviceName -> updateDeviceName(event.name)
is MeshUiEvent.UpdateTheme -> updateTheme(event.theme)
is MeshUiEvent.UpdateLanguage -> updateLanguage(event.code)
is MeshUiEvent.PermissionsGranted -> handlePermissions(event.granted)
is MeshUiEvent.ClearError -> clearError()
is MeshUiEvent.CompleteOnboarding -> completeOnboarding()
}
}
private fun startMeshNetwork() {
viewModelScope.launch {
try {
_uiState.update { it.copy(isLoading = true, statusMessage = "Starting mesh...") }
// Node starting happens automatically via observeMeshNetwork
Log.d(TAG, "Mesh network start requested")
} catch (e: Exception) {
Log.e(TAG, "Failed to start mesh", e)
_uiState.update {
it.copy(
isLoading = false,
error = "Failed to start mesh: ${e.message}"
)
}
}
}
}
private fun stopMeshNetwork() {
viewModelScope.launch {
try {
_uiState.update { it.copy(isLoading = true, statusMessage = "Stopping mesh...") }
// Node stopping happens automatically
Log.d(TAG, "Mesh network stop requested")
} catch (e: Exception) {
Log.e(TAG, "Failed to stop mesh", e)
_uiState.update {
it.copy(
isLoading = false,
error = "Failed to stop mesh: ${e.message}"
)
}
}
}
}
private fun navigateToScreen(route: String) {
_uiState.update { it.copy(currentScreen = route) }
Log.d(TAG, "Navigated to: $route")
}
private fun navigateToChat(identifier: String) {
_uiState.update {
it.copy(
shouldNavigateToChat = identifier,
currentScreen = "chatScreen/$identifier"
)
}
Log.d(TAG, "Navigating to chat: $identifier")
}
private fun updateDeviceName(name: String) {
settingPrefs.edit().putString("device_name", name).apply()
_uiState.update { it.copy(deviceName = name) }
}
private fun updateTheme(theme: String) {
settingPrefs.edit().putString("app_theme", theme).apply()
_uiState.update { it.copy(appTheme = theme) }
}
private fun updateLanguage(code: String) {
settingPrefs.edit().putString("language", code).apply()
_uiState.update { it.copy(languageCode = code) }
}
private fun handlePermissions(granted: Boolean) {
_uiState.update {
it.copy(
hasAllPermissions = granted,
permissionsRequested = true,
error = if (!granted) "Some permissions were denied" else null
)
}
}
private fun clearError() {
_uiState.update { it.copy(error = null) }
}
private fun completeOnboarding() {
meshPrefs.edit().putBoolean("hasRunBefore", true).apply()
_uiState.update { it.copy(hasRunBefore = true, showOnboarding = false) }
}
companion object {
private const val TAG = "MainViewModel"
}
}