package co.pixelbeard.theanfieldwrap.profile;

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

import java.util.ArrayList;

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.PrefUtils;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by Michael Stoddart
 * 31/12/2018.
 */
public class ProfilePresenter implements ProfileContract.Presenter {

    private ProfileContract.View mView;
    private DataRepository mRepo;

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

            mView.setPresenter(this);
        }
    }


    @Override
    public void subscribe() {
        if (mView != null && mView.checkConnection()) {
            mView.showLoader("");
            mRepo.checkUserSubscription().subscribe(new CallbackWrapper<LoginResponse>(mView) {
                @Override
                protected void onSuccess(LoginResponse loginResponse) {

                    //FOR TESTING ONLY
//                    loginResponse.getUser().setSubscriptions(new ArrayList<>());

                    PrefUtils.getInstance().storeSubs(loginResponse.getUser().getSubscriptions());
                    mView.updateSubsState();
                }

                @Override
                protected void onSuccessFalse(LoginResponse loginResponse) {
                    if (loginResponse.getMessage().equals("User is not currently subscribed")) {
                        PrefUtils.getInstance().storeSubs(new ArrayList<>());
                        mView.updateSubsState();
                    }
                }
            });
        } else {
            if (mView != null) {
                mView.onConnectionError();
            }
        }
    }

    @Override
    public void unsubscribe() {

    }

    @Override
    public void clearUserData(Context context) {
        //TODO test this
//        mRepo.clearAllData(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() {

            }
        });

    }
}
