package com.miya.fastcashier.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.miya.fastcashier.R
import com.miya.fastcashier.beans.LoginFormState
import com.miya.fastcashier.beans.LoginRequest
import com.miya.fastcashier.beans.SelfCashierAccountInfo
import com.miya.fastcashier.net.ApiRequest
import com.miya.fastcashier.net.CommonCallback
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class LoginViewModel : ViewModel() {

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

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

        viewModelScope.launch(Dispatchers.IO) {

            ApiRequest.getInstance().login(LoginRequest(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 = LoginFormState(usernameError = R.string.username_not_empty)
        } else if (!isPasswordValid(password)) {
            _loginForm.value = LoginFormState(passwordError = R.string.password_not_empty)
        } else {
            _loginForm.value = LoginFormState(isDataValid = true)
        }
    }

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

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

}