package com.gingersoft.gsa.cloud.download.mvp.presenter;

import android.app.Application;
import android.util.Log;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.base.Api;
import com.gingersoft.gsa.cloud.base.utils.constans.HttpsConstans;
import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.database.bean.Function;
import com.gingersoft.gsa.cloud.database.greendao.FoodDao;
import com.gingersoft.gsa.cloud.database.utils.FoodDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.FunctionDaoUtils;
import com.gingersoft.gsa.cloud.download.mvp.model.bean.DataDownLoadState;
import com.gingersoft.gsa.cloud.download.mvp.model.bean.FoodBean;
import com.gingersoft.gsa.cloud.download.mvp.model.bean.FunctionBean;
import com.gingersoft.gsa.cloud.download.mvp.ui.activity.DownloadActivity;
import com.gingersoft.gsa.cloud.download.mvp.ui.adapter.DataDownLoadAdapter;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;

import javax.inject.Inject;

import com.gingersoft.gsa.cloud.download.mvp.contract.DownloadContract;
import com.jess.arms.mvp.IView;
import com.jess.arms.utils.DeviceUtils;
import com.jess.arms.utils.RxLifecycleUtils;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 12/26/2019 17:59
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class DownloadPresenter extends BasePresenter<DownloadContract.Model, DownloadContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private DownloadActivity IActivity;

    private DataDownLoadAdapter mAapter;
    private List<DataDownLoadState> mList = new ArrayList<>();

    private String serverAddress;

    private int downLoadCount = 0; //下载数据计数
    private boolean downLoadState = false;

    private String urlList[] = {HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL2 + Api.download_function_list, Api.download_food_list};

    @Inject
    public DownloadPresenter(DownloadContract.Model model, DownloadContract.View rootView) {
        super(model, rootView);
        this.IActivity = (DownloadActivity) rootView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void initAdapter() {
        initDataDownItem();
        if (mAapter == null) {
            mAapter = new DataDownLoadAdapter(mApplication, mList);
            mRootView.setDownLoadListAdapter(mAapter);
        }
    }

    public void downAllList() {
        if (!DeviceUtils.netIsConnected(mApplication)) {
            mRootView.showMessage("Can not connect server, retry?");
        }
        //初始化下载记录标志
        downLoadCount = 0;
        downLoadState = false;
        down_load_data(urlList);
    }


    public void down_load_data(String[] url) {
        String restaurantId = "26";
        Observable.mergeArray(mModel.downFunctionList(), mModel.downFoodList(restaurantId))
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<Object>(mErrorHandler) {

                    @Override
                    public void onSubscribe(Disposable d) {
                        //订阅前先清空正在执行的订阅
                        unDispose();
                        //将所有 Disposable放入集中处理
                        addDispose(d);

                        for (int i = 0; i < mList.size(); i++) {
                            mList.get(i).setState(0);
                            if (i == 0) {
                                if (DeviceUtils.netIsConnected(mApplication)) {
                                    //初始化下载状态
                                    mList.get(0).setState(1);
                                }
                            }
                        }
                        mAapter.notifyDataSetChanged();

                        mRootView.getRecycleDownload().smoothScrollToPosition(0);
                    }

                    @Override
                    public void onComplete() {
                        if (downLoadState) { //下载完成
                            if (downLoadCount >= mList.size()) {//全部下载成功 返回原来的页面
                                mRootView.showMessage("下載成功");
                                endDownReturn();
                            } else {//部分下载失败
                                mRootView.showMessage("部分下載失敗，點擊刷新按鈕重新下載");
                            }
                        }
                    }

                    @Override
                    public void onNext(Object o) {
                        if (o instanceof FunctionBean) {
                            FunctionBean functionBean = (FunctionBean) o;

                            if (functionBean != null) {
                                FunctionDaoUtils functionDao = new FunctionDaoUtils(IActivity);
                                functionDao.deleteAll();
                                if (functionBean.isSuccess() && functionBean.getData() != null) {
                                    functionDao.insertMultFunction(functionBean.getData());
                                }
                            }

                            downLoadCount++;
                            mRootView.getRecycleDownload().smoothScrollToPosition(1);

                            mList.get(0).setState(2);
                            if (DeviceUtils.netIsConnected(mApplication)) {
                                mList.get(1).setState(1);
                            } else {
                                mRootView.showMessage("Can not connect server, retry?");
                            }

                        } else if (o instanceof FoodBean) {

                            FoodBean foodBean = (FoodBean) o;

                            if (foodBean != null) {
                                FoodDaoUtils foodDao = new FoodDaoUtils(IActivity);
                                foodDao.deleteAll();
                                if (foodBean.isSuccess() && foodBean.getData() != null) {
                                    foodDao.insertMultFood(foodBean.getData());
                                }
                            }

                            FoodDaoUtils foodDao = new FoodDaoUtils(IActivity);
                            List<Food> foodList = foodDao.queryAllFood();

                            downLoadCount++;
                            mRootView.getRecycleDownload().smoothScrollToPosition(1);

                            mList.get(1).setState(2);

                            downLoadState = true;

//                            if (DeviceUtils.netIsConnected(mApplication)) {
//                                mList.get(2).setState(1);
//                            } else {
//                                mRootView.showMessage("Can not connect server, retry?");
//                            }
                        }

                        mAapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable t) {
                        //这里报错需要累加一
                        downLoadCount++;
                        mRootView.showMessage("部分下載失敗，點擊刷新按鈕重新下載");
                    }
                });
    }

    private void endDownReturn() {
        CC.obtainBuilder("Component.Main")
                .setActionName("showMainActivity")
                .build()
                .call();

        mRootView.killMyself();
    }

    public void initDataDownItem() {

        //1
        DataDownLoadState downLoadState1 = new DataDownLoadState();
        downLoadState1.setState(0);
        downLoadState1.setText("功能列表");
        mList.add(downLoadState1);

        //2
        DataDownLoadState downLoadState2 = new DataDownLoadState();
        downLoadState2.setState(0);
        downLoadState2.setText("食品列表");
        mList.add(downLoadState2);
    }


}
