package com.miya.fastcashier.viewmodel

import android.util.Patterns
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.LoginRequest
import com.miya.fastcashier.beans.SelfCashierAccountInfo
import com.miya.fastcashier.net.BaseResult
import com.miya.fastcashier.service.LoginService
import com.miya.fastcashier.beans.LoginFormState
import kotlinx.coroutines.launch
import java.lang.RuntimeException

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 {
            val result = try {
                Result.success(errorHandle(LoginService.getApi().login(LoginRequest(userName,passWord,""))))
            } catch (e: Exception) {
                Result.failure(e)
            }
            // 注意这里是主线程，直接用setValue()即可
            loginLiveData.value = result
        }
    }

    //TODO 待优化
    private fun <T> errorHandle(result: BaseResult<T>): T {
        if(result.code != "200"){
            throw RuntimeException(result.msg)
        }
        return result.data;
    }

    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()
    }

}