package co.pixelbeard.theanfieldwrap.podcasts;

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

import com.tonyodev.fetch2.Download;

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

import co.pixelbeard.theanfieldwrap.data.Podcast;
import co.pixelbeard.theanfieldwrap.data.RealmPodcast;
import co.pixelbeard.theanfieldwrap.data.responses.GenericResponse;
import co.pixelbeard.theanfieldwrap.data.responses.LoginResponse;
import co.pixelbeard.theanfieldwrap.data.responses.PodcastsResponse;
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 PodcastsPresenter implements PodcastsContract.Presenter {

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

    private PodcastsContract.View mView;
    private DataRepository mRepo;

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

            mView.setPresenter(this);
        }
    }

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


            mRepo.getPodcasts(pageNum).subscribe(new CallbackWrapper<PodcastsResponse>(mView) {
                @Override
                protected void onSuccess(PodcastsResponse podcastsResponse) {
                    List<Podcast> podcasts = podcastsResponse.getPodcasts();
                    List<Podcast> nonNullPodcasts = new ArrayList<>();

                    for (Podcast podcast :
                            podcasts) {
                        if (podcast != null) {
                            nonNullPodcasts.add(podcast);
                        }
                    }

                    Podcast featuredPod = null;
                    if (pageNum == 1) {
                        featuredPod = nonNullPodcasts.get(0);
                        nonNullPodcasts.remove(0);
                    }

                    Podcast finalFeaturedPod = featuredPod;
                    new Handler().postDelayed(() -> {
                        if (mView != null) {
                            mView.setPodcastsAdapter(nonNullPodcasts, finalFeaturedPod);
                            mView.showUi();
                        }
                    }, 50);
                }

                @Override
                protected void onSuccessFalse(PodcastsResponse podcastsResponse) {
                    if (mView != null) {
                        mView.showSingleButtonDialog("Error", podcastsResponse.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());
                    if (mView != null) {
                        mView.checkSubscriptionResponse(loginResponse.getUser());
                    }
                }

                @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 getDownloadedPodcasts() {
        mRepo.getDownloadedPodcasts(podcasts -> mView.setDownloadedPodcastsAdapter(podcasts));
    }

    @Override
    public void refreshPodcasts() {

        if (mView != null) {
            if (mView.checkConnection()) {
                checkUserSubs();
                getPodcasts(1);
            } else {
                try {
                    mView.showNoConnectionHeader();
                    mView.setSwipeRefreshRefreshing(false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void downloadPodcast(Podcast podcast, Context context) {
        mRepo.downloadPodcast(podcast, context);
    }

    @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 RealmPodcast getPodcastById(long id) {
        return mRepo.getPodcastByIdLocal(id);
    }

    @Override
    public void savePodcast(Podcast podcast, Download download) {
        if (download.getUrl().equals(podcast.getPodcastFullUrl()) && download.getProgress() == 100) {
            mRepo.savePodcast(podcast, download.getFile());
        }
    }

    @Override
    public void subscribe() {
        getPodcasts(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);
    }
}
