package co.pixelbeard.theanfieldwrap.signUp.name;

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 SignUpNamePresenter implements SignUpNameContract.Presenter {

    private SignUpNameContract.View mView;
    private DataRepository mRepo;

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

            mView.setPresenter(this);
        }
    }


    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {

    }

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

    @Override
    public boolean validateFields(String firstName, String lastName, String userName, boolean shouldShowError) {

        boolean valid = true;

        if (firstName.length() == 0) {
            valid = false;
            if (shouldShowError) {
                mView.showFirstNameError();
            }
        }

        if (lastName.length() == 0) {
            valid = false;
            if (shouldShowError) {
                mView.showLastNameError();
            }
        }

        if (!ValidationUtils.isValidUsername(userName)) {
            valid = false;
            if (shouldShowError) {
                mView.showInvalidUserNameError();
            }
        }

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

        return valid;
    }

    @Override
    public void checkUserNameAvailable(String userName) {
        if (mView != null && mView.checkConnection()) {

            mRepo.checkUsernameAvailable(userName).subscribe(new CallbackWrapper<GenericResponse>(mView) {
                @Override
                protected void onSuccess(GenericResponse genericResponse) {
                    mView.setUserNameAvailable(true);
                }

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