package co.pixelbeard.theanfieldwrap.signUp.auth;

import android.content.Context;
import android.os.Handler;

import co.pixelbeard.theanfieldwrap.data.responses.GenericResponse;
import co.pixelbeard.theanfieldwrap.data.responses.LoginResponse;
import co.pixelbeard.theanfieldwrap.data.source.DataRepository;
import co.pixelbeard.theanfieldwrap.networking.CallbackWrapper;
import co.pixelbeard.theanfieldwrap.utils.PrefKey;
import co.pixelbeard.theanfieldwrap.utils.PrefUtils;
import co.pixelbeard.theanfieldwrap.utils.ValidationUtils;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by Michael Stoddart
 * 29/12/2018.
 */
public class SignUpAuthCodePresenter implements SignUpAuthCodeContract.Presenter {


    private SignUpAuthCodeContract.View mView;
    private DataRepository mRepo;

    public SignUpAuthCodePresenter(SignUpAuthCodeContract.View view, DataRepository repo) {
        if (view != null && repo != null) {
            this.mView = view;
            this.mRepo = repo;

            mView.setPresenter(this);
        }
    }


    @Override
    public boolean validateField(String authCode, boolean shouldShowError) {

        boolean valid = true;

        if (!ValidationUtils.isValidActivationCode(authCode)) {
            valid = false;
            if (shouldShowError) {
                mView.showInvalidAuthCodeError();
            }
        }

        if (valid) {
            mView.enableButton();
        } else {
            mView.disableButton();
        }
        return valid;
    }

    @Override
    public void activateUser(String email, String password, String activationCode, boolean fromLogin, boolean fromGuest) {

        if (mView != null && mView.checkConnection()) {
            mRepo.activateUser(email, activationCode).subscribe(new Observer<GenericResponse>() {
                @Override
                public void onSubscribe(Disposable d) {
                    mView.showLoader("");
                }

                @Override
                public void onNext(GenericResponse genericResponse) {
                    new Handler().postDelayed(() -> {
                        if (genericResponse.isSuccess()) {
                            PrefUtils.getInstance().putBooleanPref(PrefKey.SHOW_BONUS, true);
                            if (fromLogin) {
                                mView.hideLoader();
                                PrefUtils.getInstance().putIntPref(PrefKey.AUTH_LEVEL, 3);
                                mView.startHomeActivity();
                            } else if (ValidationUtils.isValidPassword(password)) {
                                login(email, password, PrefUtils.getInstance().getStringPref(PrefKey.ONESIGNAL_ID), fromGuest);
                            } else {
                                mView.hideLoader();
                                mView.startLoginActivity();
                            }
                        } else {
                            mView.hideLoader();
                            mView.showIncorrectAuthCodeError();
                        }
                    }, 300);

                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                    mView.hideLoader();
                    mView.showNoConnectionHeader();
                }

                @Override
                public void onComplete() {
                }
            });

        } else {
            if (mView != null)
                mView.showNoConnectionHeader();
        }
    }

    private void login(String email, String password, String deviceToken, boolean fromGuest) {

        if (mView != null && mView.checkConnection()) {

            mRepo.login(email, password).subscribe(new CallbackWrapper<LoginResponse>(mView) {
                @Override
                protected void onSuccess(LoginResponse loginResponse) {
                    mRepo.saveUserDetails(loginResponse.getUser(), loginResponse.getAuthToken());
                    if (loginResponse.getUser().getAuthLevel() == 3) {
                        if (fromGuest) {
                            mView.finishSignUpActivity();
                        } else {
                            mView.startHomeActivity();
                        }
                    }
                }

                @Override
                protected void onSuccessFalse(LoginResponse loginResponse) {
                    mView.showSingleButtonDialog("Error", loginResponse.getMessage(), null);
                }
            });


        } else {
            if (mView != null) {
                mView.showNoConnectionHeader();
            }
        }
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        this.mRepo = null;
        this.mView = null;
    }

    @Override
    public void clearUserData(Context context) {
        //Not needed
    }
}
