package com.miya.fastcashier.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fastcashier.lib_common.function.account.SelfCashierAccountInfo
import com.fastcashier.lib_common.net.CommonCallback
import com.miya.fastcashier.R
import com.miya.fastcashier.bean.LoginFormStateBean
import com.miya.fastcashier.net.param.LoginParams
import com.miya.fastcashier.net.MiyaApiRequest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class LoginViewModel : ViewModel() {

    val loginLiveData: MutableLiveData<Result<SelfCashierAccountInfo>> = MutableLiveData()
    val _loginForm = MutableLiveData<LoginFormStateBean>()
    val loginFormState: LiveData<LoginFormStateBean> = _loginForm

    fun login(userName: String, passWord: String) {

        viewModelScope.launch(Dispatchers.IO) {

            MiyaApiRequest.login(
                LoginParams(userName, passWord, ""),
                object : CommonCallback<SelfCashierAccountInfo>(){
                    override fun onSuccess(data: SelfCashierAccountInfo) {
                        loginLiveData.postValue(Result.success(data))
                    }

                    override fun onFailure(
                        errorType: Int,
                        errorCode: String?,
                        errorMessage: String?
                    ) {
                        loginLiveData.postValue(Result.failure(RuntimeException(errorMessage)))
                    }
                })
        }
    }

    fun loginDataChanged(username: String, password: String) {
        if (!isUserNameValid(username)) {
            _loginForm.value = LoginFormStateBean(usernameError = R.string.username_not_empty)
        } else if (!isPasswordValid(password)) {
            _loginForm.value = LoginFormStateBean(passwordError = R.string.password_not_empty)
        } else {
            _loginForm.value = LoginFormStateBean(isDataValid = true)
        }
    }

    private fun isUserNameValid(username: String): Boolean {
        return username.isNotBlank()
    }

    private fun isPasswordValid(password: String): Boolean {
        return password.isNotBlank()
    }

}