public class LoginPresenterImpl implements LoginContract.Presenter {
public static final String TAG = LoginPresenterImpl.class.getSimpleName();
@NonNull
private ApiService apiService;
private LoginContract.View loginView;
public LoginPresenterImpl(LoginContract.View loginView) {
this.loginView = loginView;
loginView.setPresenter(this);
}
@Override
public void start() {
}
@Override
public void login(final String username, final String password) {
if (false == isUsernameValid(username)) {
return;
}
if (false == isPasswordValid(password)) {
return;
}
// todo: uncomment when back end will be available
//requestLogin(username, password);
fakeLogin(username, password);
}
private boolean isUsernameValid(String username) {
if (TextUtils.isEmpty(username)) {
loginView.showUsernameValidationError(R.string.validation_error_empty_field);
return false;
}
return true;
}
private boolean isPasswordValid(String password) {
if (TextUtils.isEmpty(password)) {
loginView.showPasswordValidationError(R.string.validation_error_empty_field);
return false;
}
if (password.length() < 8) {
loginView.showPasswordValidationError(R.string.validation_error_to_few_chars);
return false;
}
if (false == isPasswordMatchesPattern(password)) {
loginView.showPasswordValidationError(R.string.validation_error_do_not_use_special_chars);
return false;
}
return true;
}
private boolean isPasswordMatchesPattern(String password) {
// only alphabeticals or digits, no special chars
final String pattern = "^[a-zA-Z0-9]*$";
return password.matches(pattern);
}
private void requestLogin(String username, String password) {
LogUtil.d(TAG, "requestLogin: " + username + ", " + password);
loginView.showProgress(true);
// Initialize the city endpoint
apiService = new RetrofitHelper().getLoginService();
apiService.login(username, password).enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
LogUtil.d(TAG, "onResponse: " + response);
String token = null;
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
token = jsonObject.getString("token");
} catch (JSONException e) {
e.printStackTrace();
}
loginView.showProgress(false);
// todo: save token to prefs
loginView.onLoginSuccess();
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
LogUtil.d(TAG, "onFailure");
loginView.showProgress(false);
loginView.onLoginError(t.getMessage());
}
});
}
private void fakeLogin(String username, String password) {
loginView.showProgress(true);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
loginView.showProgress(false);
onFakeSuccess();
}
}, 3000);
}
private void onFakeSuccess() {
loginView.onLoginSuccess();
}
}