package ch.mod_p.sre24.e5.ui.login;

import android.content.Context;
import android.util.Patterns;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import ch.mod_p.sre24.e5.R;
import ch.mod_p.sre24.e5.data.LoginRepository;
import ch.mod_p.sre24.e5.data.Result;
import ch.mod_p.sre24.e5.data.model.LoggedInUser;

/* loaded from: classes.dex */
public class LoginViewModel extends ViewModel {
    private final LoginRepository loginRepository;
    private final MutableLiveData<LoginFormState> loginFormState = new MutableLiveData<>();
    private final MutableLiveData<LoginResult> loginResult = new MutableLiveData<>();

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

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

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

    public void login(Context context, String str, String str2) {
        Result<LoggedInUser> login = this.loginRepository.login(context, str, str2);
        if (login instanceof Result.Success) {
            this.loginResult.setValue(new LoginResult(new LoggedInUserView(((LoggedInUser) ((Result.Success) login).getData()).getDisplayName())));
        } else {
            this.loginResult.setValue(new LoginResult(Integer.valueOf(R.string.login_failed)));
        }
    }

    public void loginDataChanged(String str, String str2) {
        if (!isUserNameValid(str)) {
            this.loginFormState.setValue(new LoginFormState(Integer.valueOf(R.string.invalid_username), null));
        } else if (!isPasswordValid(str2)) {
            this.loginFormState.setValue(new LoginFormState(null, Integer.valueOf(R.string.invalid_password)));
        } else {
            this.loginFormState.setValue(new LoginFormState(true));
        }
    }

    private boolean isUserNameValid(String str) {
        if (str == null) {
            return false;
        }
        if (str.contains("@")) {
            return Patterns.EMAIL_ADDRESS.matcher(str).matches();
        }
        return !str.trim().isEmpty();
    }

    private boolean isPasswordValid(String str) {
        return str != null && str.trim().length() > 5;
    }
}
