/*
 * Copyright © All Contributors. See LICENSE and AUTHORS in the root directory for details.
 */

package at.bitfire.davdroid.ui.setup

import androidx.compose.foundation.text.input.TextFieldState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import at.bitfire.davdroid.settings.Credentials
import at.bitfire.davdroid.util.DavUtils.toURIorNull
import at.bitfire.synctools.util.SensitiveString.Companion.toSensitiveString
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import dagger.hilt.android.lifecycle.HiltViewModel

@HiltViewModel(assistedFactory = EmailLoginViewModel.Factory::class)
class EmailLoginViewModel @AssistedInject constructor(
    @Assisted val initialLoginInfo: LoginInfo
): ViewModel() {

    @AssistedFactory
    interface Factory {
        fun create(loginInfo: LoginInfo): EmailLoginViewModel
    }

    data class UiState(
        val email: String = "",
        val password: TextFieldState = TextFieldState()
    ) {
        val uri = "mailto:$email".toURIorNull()

        val canContinue     // we have to use get() because password is not immutable
            get() = uri != null && password.text.toString().isNotEmpty()

        fun asLoginInfo(): LoginInfo {
            return LoginInfo(
                baseUri = uri,
                credentials = Credentials(
                    username = email,
                    password = password.text.toSensitiveString()
                )
            )
        }
    }

    var uiState by mutableStateOf(UiState())
        private set

    init {
        uiState = uiState.copy(
            email = initialLoginInfo.credentials?.username ?: "",
            password = TextFieldState(initialLoginInfo.credentials?.password?.asString() ?: "")
        )
    }

    fun setEmail(email: String) {
        uiState = uiState.copy(email = email)
    }

}