79 lines
2.4 KiB
Kotlin
79 lines
2.4 KiB
Kotlin
package com.example.tvcontroller
|
|
|
|
import androidx.compose.runtime.getValue
|
|
import androidx.compose.runtime.mutableStateOf
|
|
import androidx.compose.runtime.setValue
|
|
import androidx.lifecycle.ViewModel
|
|
import androidx.lifecycle.ViewModelProvider
|
|
import androidx.lifecycle.viewModelScope
|
|
import com.example.tvcontroller.services.DeviceService
|
|
import kotlinx.coroutines.launch
|
|
|
|
class SettingsViewModel(private val deviceService: DeviceService) : ViewModel() {
|
|
var serverAddress by mutableStateOf(deviceService.getServerAddress())
|
|
private set
|
|
var deviceName by mutableStateOf(android.os.Build.MANUFACTURER + " " + android.os.Build.MODEL)
|
|
private set
|
|
var registrationCode by mutableStateOf("")
|
|
private set
|
|
var connectionState by mutableStateOf(Settings.ConnectionState.Unregistered)
|
|
private set
|
|
|
|
init {
|
|
updateConnectionState()
|
|
viewModelScope.launch {
|
|
updateDeviceInfo()
|
|
}
|
|
}
|
|
|
|
fun connect() {
|
|
//Log.i("SettingsScreen", "Save settings: $serverUrl, $deviceName, $registrationCode")
|
|
viewModelScope.launch {
|
|
deviceService.setServerAddress(serverAddress)
|
|
deviceService.createIntegration(deviceName, registrationCode)
|
|
updateConnectionState()
|
|
}
|
|
}
|
|
|
|
private fun updateConnectionState() {
|
|
connectionState = if (deviceService.getToken().isEmpty()) {
|
|
Settings.ConnectionState.Unregistered
|
|
return
|
|
} else {
|
|
Settings.ConnectionState.Registered
|
|
}
|
|
}
|
|
|
|
private suspend fun updateDeviceInfo() {
|
|
if (connectionState == Settings.ConnectionState.Unregistered) return
|
|
val integration = deviceService.getIntegration()
|
|
if (integration == null) {
|
|
connectionState = Settings.ConnectionState.Unregistered
|
|
return
|
|
}
|
|
deviceName = integration.name
|
|
}
|
|
|
|
fun onServerAddressChanged(url: String) {
|
|
serverAddress = url
|
|
}
|
|
|
|
fun onDeviceNameChanged(name: String) {
|
|
deviceName = name
|
|
}
|
|
|
|
fun onRegistrationCodeChanged(code: String) {
|
|
registrationCode = code
|
|
}
|
|
|
|
companion object {
|
|
fun provideFactory(
|
|
deviceService: DeviceService,
|
|
) = object : ViewModelProvider.Factory {
|
|
@Suppress("UNCHECKED_CAST")
|
|
override fun <T : ViewModel> create(modelClass: Class<T>): T {
|
|
return SettingsViewModel(deviceService) as T
|
|
}
|
|
}
|
|
}
|
|
} |