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

import android.app.Application;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.common.bean.FoodBean;
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.database.bean.Combo;
import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.database.bean.FoodModifier;
import com.gingersoft.gsa.cloud.database.bean.Modifier;
import com.gingersoft.gsa.cloud.database.utils.ComboDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.FoodDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.FoodModifierDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.FunctionDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.ModifierDaoUtils;
import com.gingersoft.gsa.cloud.download.mvp.model.bean.ComboRespone;
import com.gingersoft.gsa.cloud.download.mvp.model.bean.DataDownLoadState;
import com.gingersoft.gsa.cloud.download.mvp.model.bean.FoodModifierRespone;
import com.gingersoft.gsa.cloud.download.mvp.model.bean.FunctionRespone;
import com.gingersoft.gsa.cloud.download.mvp.model.bean.ModifierRespone;
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.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.utils.DeviceUtils;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.ArrayList;
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[] downTitles = {"功能列表", "食品列表", "食品細項", "套餐", "食品細項關係"};

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

    private List<Food> foodList;
//    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();
    }

    public void down_load_data() {
        int restaurantId = GsaCloudApplication.getRestaurantId(IActivity);
        Observable.mergeArray(mModel.downFunctionList(), mModel.downFoodList(restaurantId)
                , mModel.downModifier(restaurantId), mModel.downCombo(restaurantId),
                mModel.downFoodModifier(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 FunctionRespone) {
                            FunctionRespone functionBean = (FunctionRespone) 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());
                                }
                            }

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

                            mList.get(1).setState(2);
                            if (DeviceUtils.netIsConnected(mApplication)) {
                                mList.get(2).setState(1);
                            } else {
                                mRootView.showMessage("Can not connect server, retry?");
                            }
                        } else if (o instanceof ModifierRespone) {
                            ModifierRespone modifier = (ModifierRespone) o;
                            if (modifier != null) {
                                ModifierDaoUtils modifierDao = new ModifierDaoUtils(IActivity);
                                modifierDao.deleteAll();
                                if (modifier.isSuccess() && modifier.getData() != null) {
                                    modifierDao.insertMultModifier(modifier.getData());
                                }
                            }

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

                        } else if (o instanceof ComboRespone) {
                            ComboRespone combo = (ComboRespone) o;
                            if (combo != null) {
                                ComboDaoUtils comboDao = new ComboDaoUtils(IActivity);
                                comboDao.deleteAll();
                                if (combo.isSuccess() && combo.getData() != null) {
                                    comboDao.insertMultCombo(combo.getData());
                                }
                            }

                            downLoadCount++;
                            mRootView.getRecycleDownload().smoothScrollToPosition(1);
                            mList.get(3).setState(2);
                            if (DeviceUtils.netIsConnected(mApplication)) {
                                mList.get(4).setState(1);
                            } else {
                                mRootView.showMessage("Can not connect server, retry?");
                            }
                        } else if (o instanceof FoodModifierRespone) {
                            FoodModifierRespone foodModifier = (FoodModifierRespone) o;
                            if (foodModifier != null) {
                                FoodModifierDaoUtils foodModifierDao = new FoodModifierDaoUtils(IActivity);
                                foodModifierDao.deleteAll();
                                if (foodModifier.isSuccess() && foodModifier.getData() != null) {
                                    foodModifierDao.insertMultFoodModifier(foodModifier.getData());
                                }
                            }
                            downLoadCount++;
                            mRootView.getRecycleDownload().smoothScrollToPosition(1);
                            downLoadState = true;
                        }

                        mAapter.notifyDataSetChanged();
                    }

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

//                        downAllList();
                    }
                });
    }

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

    public void initDataDownItem() {
        for (int i = 0; i < downTitles.length; i++) {
            DataDownLoadState downLoadState1 = new DataDownLoadState();
            downLoadState1.setState(0);
            downLoadState1.setText(downTitles[i]);
            mList.add(downLoadState1);
        }
    }

}
