package co.pixelbeard.theanfieldwrap.splash;

import android.content.Context;

import java.util.ArrayList;

import co.pixelbeard.theanfieldwrap.data.responses.LoginResponse;
import co.pixelbeard.theanfieldwrap.data.source.DataRepository;
import co.pixelbeard.theanfieldwrap.utils.PrefKey;
import co.pixelbeard.theanfieldwrap.utils.PrefUtils;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by Michael Stoddart
 * 17/12/2018.
 */
public class SplashPresenter implements SplashContract.Presenter {

    private SplashContract.View mView;
    private DataRepository mRepo;

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

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

    @Override
    public void checkUserSubs() {

        mRepo.checkUserSubscription().subscribe(new Observer<LoginResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(LoginResponse loginResponse) {
                if (loginResponse.isSuccess()) {
                    mRepo.saveUserDetails(loginResponse.getUser(), PrefUtils.getInstance().getStringPref(PrefKey.AUTH_TOKEN));
                } else {
                    PrefUtils.getInstance().storeSubs(new ArrayList<>());
                }
            }

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

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {

    }

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