package co.pixelbeard.theanfieldwrap.login;

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

import co.pixelbeard.theanfieldwrap.R;
import co.pixelbeard.theanfieldwrap.data.responses.GuestUserResponse;
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.ConnectionUtils;
import co.pixelbeard.theanfieldwrap.utils.ValidationUtils;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by Michael Stoddart
 * 21/12/2018.
 */
public class LoginPresenter implements LoginContract.Presenter {


    private static final String TAG = LoginPresenter.class.getSimpleName();

    private LoginContract.View mView;
    private DataRepository mRepo;


    public LoginPresenter(LoginContract.View view, DataRepository repo) {
        if (view != null) {
            this.mView = view;
            this.mRepo = repo;

            mView.setPresenter(this);
        } else {
            throw new RuntimeException();
        }
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        mRepo.onDestroyRepo();
    }

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

    @Override
    public void backClicked() {
        mView.goBack();
    }

    @Override
    public void forgotPasswordClicked(String email) {
        mView.startForgotPasswordActivity(email);
    }

    @Override
    public void skipLoginClicked() {

        if (mView != null && mView.checkConnection()) {
            mView.showLoader("");
            mRepo.registerGuestUser().subscribe(new CallbackWrapper<GuestUserResponse>(mView) {
                @Override
                protected void onSuccess(GuestUserResponse guestUserResponse) {
                    mRepo.saveGuestUserDetails(guestUserResponse.getUserName(), guestUserResponse.getUserAuthToken());
                    mView.startHomeActivity();
                }

                @Override
                protected void onSuccessFalse(GuestUserResponse guestUserResponse) {
                    mView.showSingleButtonDialog("Error", guestUserResponse.getMessage());
                }
            });
        } else {
            if (mView != null) {
                mView.onConnectionError();
            }
        }
    }

    @Override
    public void loginClicked(String email, String password, boolean fromGuest) {

        if (mView != null && mView.checkConnection()) {
            if (checkValidated(email, password, true)) {

                mRepo.login(email, password).subscribe(new Observer<LoginResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.d(TAG + " login", "onSubscribe");
                        if (mView != null) {
                            mView.showLoader("");
                        }
                    }

                    @Override
                    public void onNext(LoginResponse loginResponse) {
                        if (mView != null) {
                            if (loginResponse.isSuccess()) {
                                mView.showLoginSuccess();
                            } else {
                                mView.hideLoader();
                            }
                        }
                        new Handler().postDelayed(() -> {
                            if (mView != null) {
                                if (loginResponse.isSuccess()) {
                                    mRepo.saveUserDetails(loginResponse.getUser(), loginResponse.getAuthToken());

                                    if (loginResponse.getUser().getAuthLevel() >= 3) {
                                        if (fromGuest) {
                                            mView.finishLoginActivity();
                                        } else {
                                            mView.startHomeActivity();
                                        }
                                    } else {
                                        mView.startSignUpActivity(email);
                                    }
                                } else {
                                    if (loginResponse.getMessage().equalsIgnoreCase("You have reached your limit of devices for your account.")) {

                                        if (loginResponse.getDeviceList() != null) {

                                            mView.showDeviceLimitDialog(loginResponse.getDeviceList());
                                        }
                                    } else {
                                        mView.onUnknownError(loginResponse.getMessage());
                                    }
                                }
                            }
                        }, 300);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG + " login", "onError");
                        e.printStackTrace();
                        if (mView != null) {
                            mView.hideLoader();
                            mView.showSingleButtonDialog("Error", e.getMessage());
                        }
                    }

                    @Override
                    public void onComplete() {
                        Log.d(TAG + " login", "onComplete");
                    }
                });
            }
        } else {
            if (mView != null) {
                mView.onConnectionError();
            }
        }
    }

    @Override
    public boolean checkValidated(String email, String password, boolean shouldShowError) {

        boolean validated = true;

        if (mView != null) {
            if (ValidationUtils.isValidEmail(email)) {

                if (ValidationUtils.isValidPassword(password)) {
                    mView.enableButton();
                } else {
                    validated = false;
                    if (shouldShowError) {
                        mView.showPasswordError(mView.getStringFromResource(R.string.invalid_password));
                    }
                }

            } else {
                validated = false;
                if (shouldShowError) {
                    mView.showEmailError(mView.getStringFromResource(R.string.invalid_email));
                }
            }

            if (validated) {
                mView.enableButton();
            } else {
                mView.disableLoginButton();
            }

        } else {
            validated = false;
        }
        return validated;
    }

    @Override
    public boolean checkConnection(Context mContext) {
        return ConnectionUtils.userHasConnection(mContext);
    }
}
