package co.pixelbeard.theanfieldwrap.signUp.emailPassword;

import android.content.Context;

import co.pixelbeard.theanfieldwrap.data.responses.GenericResponse;
import co.pixelbeard.theanfieldwrap.data.source.DataRepository;
import co.pixelbeard.theanfieldwrap.networking.CallbackWrapper;
import co.pixelbeard.theanfieldwrap.utils.ValidationUtils;

/**
 * Created by Michael Stoddart
 * 29/12/2018.
 */
public class SignUpEmailPasswordPresenter implements SignUpEmailPasswordContract.Presenter {

    private SignUpEmailPasswordContract.View mView;
    private DataRepository mRepo;


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

            mView.setPresenter(this);
        }
    }

    @Override
    public boolean validateFields(String email, String password, String country, boolean shouldShowError) {
        boolean valid = true;

        if (!ValidationUtils.isValidEmail(email)) {
            valid = false;
            if (shouldShowError) {
                mView.showInvalidEmailError();
            }
        }

        if (!ValidationUtils.isValidPassword(password)) {
            valid = false;
            if (shouldShowError) {
                mView.showPasswordError();
            }
        }

        if (country == null || country.equals("")) {
            valid = false;
            if (shouldShowError) {
                mView.showCountryError();
            }
        }

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

        return valid;
    }

    @Override
    public void checkEmailAvailable(String email) {

        if (mView != null && mView.checkConnection()) {
            mRepo.checkEmailAvailable(email).subscribe(new CallbackWrapper<GenericResponse>(mView) {
                @Override
                protected void onSuccess(GenericResponse genericResponse) {
                    mView.setEmailAvailable(true);
                }

                @Override
                protected void onSuccessFalse(GenericResponse genericResponse) {
                    mView.setEmailAvailable(false);
                    mView.showEmailNotAvailableError();
                }
            });
        } else {
            if (mView != null)
                mView.showNoConnectionHeader();
        }


    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {

    }

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