package co.pixelbeard.theanfieldwrap.accountDetails;

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

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.PrefKey;
import co.pixelbeard.theanfieldwrap.utils.PrefUtils;
import co.pixelbeard.theanfieldwrap.utils.ValidationUtils;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class AccountDetailsPresenter implements AccountDetailsContract.Presenter {

    private AccountDetailsContract.View mView;
    private DataRepository mRepo;

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

            mView.setPresenter(this);
        }
    }

    @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) {
        mRepo.checkUsernameAvailable(userName).subscribe(new Observer<GenericResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(GenericResponse genericResponse) {
                if (genericResponse.isSuccess()) {
                    mView.setUserNameAvailable(true);
                } else {
                    mView.setUserNameAvailable(false);
                    mView.showUserNameNotAvailableError();
                }
            }

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

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public void updateUserDetails(String firstName, String lastName, String userName) {
        if (mView != null && mView.checkConnection()) {
            mView.showLoader("");
            mRepo.updateUserDetails(firstName, lastName, userName).subscribe(new CallbackWrapper<GenericResponse>(mView) {
                @Override
                protected void onSuccess(GenericResponse genericResponse) {
                    mRepo.saveUserDetails(firstName, lastName, userName);
                    new Handler().postDelayed(() -> {
                        if (mView != null) {
                            mView.goBack();
                        }
                    }, 300);
                }

                @Override
                protected void onSuccessFalse(GenericResponse genericResponse) {
                    if (mView != null) {
                        mView.showSingleButtonDialog("Error", genericResponse.getMessage());
                    }
                }
            });

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

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

        PrefUtils prefs = PrefUtils.getInstance();

        if (firstName == null || lastName == null || userName == null) {
            return false;
        }


        String storedFirstName = prefs.getStringPref(PrefKey.FIRSTNAME);
        String storedLastName = prefs.getStringPref(PrefKey.LASTNAME);
        String storedUserName = prefs.getStringPref(PrefKey.USERNAME);

        if (storedFirstName == null) {
            storedFirstName = "";
        }
        if (storedLastName == null) {
            storedLastName = "";
        }
        if (storedUserName == null) {
            storedUserName = "";
        }

        boolean changed = !storedFirstName.equals(firstName) ||
                !storedLastName.equals(lastName) ||
                !storedUserName.equals(userName);

        return changed;
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {

    }

    @Override
    public void clearUserData(Context context) {
        mRepo.logout().subscribe(new Observer<GenericResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(GenericResponse genericResponse) {
                Log.d("LOGOUT", genericResponse.getMessage());
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

        //TODO test this
//        mRepo.clearAllData(context);
    }
}
