package com.yidianling.dynamic.trendList;

import android.text.TextUtils;
import android.view.View;

import com.google.gson.Gson;
import com.yidianling.common.tools.LogUtil;
import com.yidianling.dynamic.common.net.DynamicApiUtils;
import com.yidianling.dynamic.model.Command;
import com.yidianling.dynamic.model.TrendsListBean;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.ydl.ydlcommon.utils.YDLCacheUtils;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Jim on 2017/11/10 0010.
 */

public class TrendsListInteractor {

    private CompositeDisposable compositeSubscription = new CompositeDisposable();
    private ITrendsListPresenter.onDataLoadCallBackListener callBack;

    public void setCallBack(ITrendsListPresenter.onDataLoadCallBackListener callBack) {
        this.callBack = callBack;
    }


    private void addSubscription(Disposable d) {
        compositeSubscription.add(d);
    }

    public TrendsListInteractor() {
    }

    /**
     * 加载本地缓存
     * @param tab 1.最新（推荐） 2.热门
     */
    public void localData(int tab){
//        YDLAsyncUtils.Companion.asyncAsResult(new YDLAsyncUtils.AsyncObjecyerResult() {
//            @NotNull
//            @Override
//            public Object doAsyncAction() {
//                switch (tab){
//                    case 1:
//                        return YDLCacheUtils.Companion.getAskListNewstData();
//                    case 2:
//                        return YDLCacheUtils.Companion.getAskListPopularData();
//                        default:
//                            return YDLCacheUtils.Companion.getAskListNewstData();
//                }
//            }
//
//            @Override
//            public void asyncResult(@Nullable Object object) {
//                if (object instanceof String) {
//                    String cache = (String) object;
//                    if (!TextUtils.isEmpty(cache)) {
//
//                        TrendsListBean dataBean = new Gson().fromJson(cache,TrendsListBean.class);
//                        if (null != callBack && dataBean != null) {
//                            callBack.onTrendsListFetched(dataBean);
//                        }
//                    }
//                }
//            }
//        });
    }

    /**
     * 更新缓存
     * @param tab       1.最新（推荐） 2.热门
     * @param dataBean  数据bean
     */
    private void updateCache(int tab,TrendsListBean dataBean){
        String json = new Gson().toJson(dataBean);
        if (!TextUtils.isEmpty(json)){
            switch (tab){
                case 1:
                    YDLCacheUtils.Companion.saveAskListNewstData(json);
                    break;
                case 2:
                    YDLCacheUtils.Companion.saveAskListPopularData(json);
                    break;
            }
        }
    }

    public void fetchPhpTrendsInfo(int tab, int page, int topicId, int lastId) {
        Command.TrendListCmd request = new Command.TrendListCmd(String.valueOf(tab), page, String.valueOf(topicId), String.valueOf(lastId));
        addSubscription(DynamicApiUtils.fetchPhpTrendList(request)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(trendsListBean -> {
                    LogUtil.i("get Response: " + trendsListBean.toString());
                    if (callBack != null) {
                        callBack.onTrendsListFetched(trendsListBean);
                    }
                }, throwable -> {
                    LogUtil.i("error: " + throwable.toString());
                    if (callBack != null) {
                        callBack.onTrendsListFetchFialed(throwable);
                    }
                }));
    }

    public void fetchTrendsInfo(int tab, int page, int topicId, int lastId) {
        Command.TrendListCmd request = new Command.TrendListCmd(String.valueOf(tab), page, String.valueOf(topicId), String.valueOf(lastId));
        //获取话题（问答）列表
        addSubscription(DynamicApiUtils.fetchTrendList(request)
                .compose(RxUtils.resultJavaData())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(trendsListBean -> {
//                    LogUtil.i("get Response: " + trendsListBean.toString());
                    if (callBack != null) {
                        //更新缓存
//                        updateCache(tab,trendsListBean);
                        callBack.onTrendsListFetched(trendsListBean);
                    }
                }, throwable -> {
                    LogUtil.i("error: " + throwable.toString());
                    if (callBack != null) {
                        callBack.onTrendsListFetchFialed(throwable);
                    }
                }));
    }

    public void fetchTopicListInfo(int cat, int my) {
        Command.AllTopicCmd request = new Command.AllTopicCmd(String.valueOf(cat), String.valueOf(cat));
        addSubscription(DynamicApiUtils.fetchTopicList(request)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(topicListDataBaseResponse -> {
                    LogUtil.i("get Response: " + topicListDataBaseResponse.toString());
                    if (callBack != null) {
                        callBack.onRecommendTopicFetched(topicListDataBaseResponse);
                    }
                }, throwable -> {
                    LogUtil.i("error: " + throwable.toString());
                    if (callBack != null) {
                        callBack.onRecommendTopicFetchFailed(throwable);
                    }
                }));
    }

    /**
     * 点赞
     */
    public void doLikeAction(final View view, final int position, int trendId, final List<TrendsListBean.Trend> mDatas) {
        final Command.ZanAction cmd = new Command.ZanAction("2", String.valueOf(trendId));
        addSubscription(DynamicApiUtils.zanAction(cmd)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(zanResultResponse -> {
                    if (callBack != null) {
                        callBack.onLikeActionFetchedResult(view, position, zanResultResponse, mDatas);
                    }
                }, throwable -> {
                    if (callBack!=null){
                        callBack.onLikeActionFailed(throwable);
                    }
                }));
    }

    public void fetchUserTrendsList(String uid, int page, int tab) {
        Command.UserTrendCmd cmd = new Command.UserTrendCmd(uid, tab, page);
        addSubscription(DynamicApiUtils.getUserTrend(cmd)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(listBaseResponse -> {
                    if (callBack != null) {
                        callBack.onUserTrendFetched(listBaseResponse);
                    }
                }, throwable -> {
                    if (callBack != null) {
                        callBack.onUserTrendFetchFailed(throwable);
                    }
                }));
    }

    public void onDestroy() {
        compositeSubscription.dispose();
    }
}
