package com.pixelized.biblib.ui.screen.authentication.viewModel

import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import com.pixelized.biblib.BuildConfig
import com.pixelized.biblib.repository.credential.ICredentialRepository
import com.pixelized.biblib.ui.screen.authentication.AuthenticationFormUIO
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject

@HiltViewModel
class AuthenticationFormViewModel @Inject constructor(
    private val credentialRepository: ICredentialRepository,
) : ViewModel() {

    private val _login = mutableStateOf(credentialRepository.rememberedLogin)
    private val _password = mutableStateOf(credentialRepository.rememberedPassword)
    private val _remember = mutableStateOf(credentialRepository.rememberCredential)

    val form: AuthenticationFormUIO = AuthenticationFormUIO(
        login = _login,
        password = _password,
        remember = _remember,
    )

    fun onLoginChange(login: String) {
        // update login in the repository
        if (_remember.value) {
            credentialRepository.login = login
        }
        // update the UI State
        _login.value = login
    }

    fun onPasswordChange(password: String) {
        // update password in the repository
        if (_remember.value) {
            credentialRepository.password = password
        }
        // update the UI State
        _password.value = password
    }

    fun onRememberChange(remember: Boolean) {
        // save the remember state in the repository
        credentialRepository.rememberCredential = remember
        // update login & password  in the repository
        if (remember.not()) {
            credentialRepository.login = null
            credentialRepository.password = null
        } else {
            credentialRepository.login = _login.value
            credentialRepository.password = _password.value
        }
        // update the UI State
        _remember.value = remember
    }

    private val ICredentialRepository.rememberedLogin: String
        get() = when {
            rememberCredential -> login ?: ""
            BuildConfig.DEBUG -> "ThomasTest"
            else -> ""
        }

    private val ICredentialRepository.rememberedPassword: String
        get() = when {
            rememberCredential -> password ?: ""
            BuildConfig.DEBUG -> "MotDePasseRandom$2"
            else -> ""
        }
}