package tr.dhee.abox.demo.ui.login;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import tr.dhee.abox.demo.R;
import tr.dhee.abox.demo.data.LoginRepository;
import tr.dhee.abox.demo.data.Result;
import tr.dhee.abox.demo.data.model.LoggedInUser;

public class LoginViewModel extends ViewModel {

    private MutableLiveData<LoginFormState> loginFormState = new MutableLiveData<>();
    private MutableLiveData<LoginResult> loginResult = new MutableLiveData<>();
    private LoginRepository loginRepository;

    LoginViewModel(LoginRepository loginRepository) {
        this.loginRepository = loginRepository;
    }

    LiveData<LoginFormState> getLoginFormState() {
        return loginFormState;
    }

    LiveData<LoginResult> getLoginResult() {
        return loginResult;
    }

    public void login(String username, String password) {
        // 后台线程执行 SDK 登录, 结果回到主线程再更新 LiveData
        loginRepository.login(username, password, result -> {
            if (result instanceof Result.Success) {
                LoggedInUser data = ((Result.Success<LoggedInUser>) result).getData();
                loginResult.postValue(new LoginResult(new LoggedInUserView(data.getDisplayName())));
            } else {
                // 取出 LoginDataSource 里封装的中文错误提示
                Exception err = ((Result.Error) result).getError();
                loginResult.postValue(new LoginResult(err != null ? err.getMessage() : "登录失败"));
            }
        });

    }

    public void loginDataChanged(String username, String password) {
        if (!isUserNameValid(username)) {
            loginFormState.setValue(new LoginFormState(R.string.invalid_username, null));
        } else if (!isPasswordValid(password)) {
            loginFormState.setValue(new LoginFormState(null, R.string.invalid_password));
        } else {
            loginFormState.setValue(new LoginFormState(true));
        }
    }

    // 仅校验不为空
    private boolean isUserNameValid(String username) {
        return username != null && !username.trim().isEmpty();
    }

    // 仅校验不为空
    private boolean isPasswordValid(String password) {
        return password != null && !password.trim().isEmpty();
    }
}
