package net.buzzert.kordophonedroid.ui.settings

import androidx.compose.runtime.MutableState
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import net.buzzert.kordophonedroid.ui.shared.ServerAuthentication
import net.buzzert.kordophonedroid.ui.shared.ServerConfigRepository
import javax.inject.Inject

@HiltViewModel
class SettingsViewModel @Inject constructor(
    val serverConfigRepository: ServerConfigRepository
) : ViewModel() {
    private val _serverPreference: MutableStateFlow<String> = MutableStateFlow("")
    var serverPreference = _serverPreference.asStateFlow()

    private val _usernamePreference: MutableStateFlow<String> = MutableStateFlow("")
    var usernamePreference = _usernamePreference.asStateFlow()

    private val _passwordPreference: MutableStateFlow<String> = MutableStateFlow("")
    var passwordPreference = _passwordPreference.asStateFlow()

    init {
        val serverConfig = serverConfigRepository.serverConfig.value
        serverConfig.serverName?.let { _serverPreference.value = it }
        serverConfig.authentication?.let {
            _usernamePreference.value = it.username
            _passwordPreference.value = it.password
        }
    }

    fun saveServerPreference(serverName: String) {
        _serverPreference.value = serverName

        serverConfigRepository.applyConfig {
            this.serverName = serverName
        }
    }

    fun saveAuthenticationPreferences(username: String, password: String) {
        _usernamePreference.value = username
        _passwordPreference.value = password

        serverConfigRepository.applyConfig {
            this.authentication = ServerAuthentication(username, password)
        }
    }
}