package co.pixelbeard.theanfieldwrap.writing;

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

import java.util.ArrayList;
import java.util.List;

import co.pixelbeard.theanfieldwrap.data.Article;
import co.pixelbeard.theanfieldwrap.data.responses.ArticlesResponse;
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 WritingPresenter implements WritingContract.Presenter {

    private static final String TAG = WritingPresenter.class.getSimpleName();

    private WritingContract.View mView;
    private DataRepository mRepo;

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

            mView.setPresenter(this);
        }
    }


    @Override
    public void getArticles(int pageNum) {
        if (mView != null && mView.checkConnection()) {
            if (pageNum == 1) {
                mView.showLoader("");
            }
//            else {
//                mView.setSwipeRefreshRefreshing(true);
//            }


            mRepo.getArticles(pageNum).subscribe(new CallbackWrapper<ArticlesResponse>(mView) {
                @Override
                protected void onSuccess(ArticlesResponse articlesResponse) {

                    List<Article> articles = articlesResponse.getArticles();

                    Article featuredArticle = null;
                    if (pageNum == 1) {
                        for (int i = 0; i < articles.size(); i++) {
                            Article article = articles.get(i);

                            if (article.isFeatured()) {
                                featuredArticle = article;
                                articles.remove(i);
                                break;
                            }
                        }

                        if (featuredArticle == null) {
                            featuredArticle = articles.get(0);
                            articles.remove(0);
                        }
                    }

                    Article finalFeaturedArticle = featuredArticle;
                    new Handler().postDelayed(() -> {

                        if (mView != null) {
                            mView.setWritingAdapter(articles, finalFeaturedArticle);
                            mView.showUi();
                        }
                    }, 50);
                }


                @Override
                protected void onSuccessFalse(ArticlesResponse articlesResponse) {
                    if (mView != null) {
                        mView.showSingleButtonDialog("Error", articlesResponse.getMessage());
                    }
                }
            });
        } else {
            if (mView != null) {
                mView.onConnectionError();
            }
        }
    }

    @Override
    public void checkUserSubs() {
        if (mView != null && mView.checkConnection()) {
            mRepo.checkUserSubscription().subscribe(new CallbackWrapper<LoginResponse>(mView) {
                @Override
                protected void onSuccess(LoginResponse loginResponse) {
                    PrefUtils.getInstance().storeSubs(loginResponse.getUser().getSubscriptions());
                }

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

    }

    @Override
    public void refreshArticles() {
        if (mView != null) {
            if (mView.checkConnection()) {
                checkUserSubs();
                getArticles(1);
            } else {
                try {
                    mView.showNoConnectionHeader();
                    mView.setSwipeRefreshRefreshing(false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void recordAnalytic(String type, String variable, String secondVar) {
        mRepo.recordAnalytic(type, variable, secondVar).subscribe(new Observer<GenericResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(GenericResponse genericResponse) {
                if (genericResponse != null) {
                    Log.d("ANALYTIC: " + type, genericResponse.getMessage());
                }
            }

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

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public void subscribe() {
        getArticles(1);
    }

    @Override
    public void unsubscribe() {
        mRepo.onDestroyRepo();
        mView = null;
    }

    @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);
    }
}
