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

import android.app.Application;

import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.main.mvp.contract.EditFoodContract;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.FoodGroupBean;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.SummaryBean;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.TimePeriodBean;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

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

import javax.inject.Inject;

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

import static com.gingersoft.gsa.cloud.main.mvp.ui.fragment.menu.BaseFoodMenuFragment.SELECT_FOOD_TYPE;
import static com.gingersoft.gsa.cloud.main.mvp.ui.fragment.menu.BaseFoodMenuFragment.SELECT_TIME_PERIOD;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 11/03/2020 11:07
 * <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>
 * ================================================
 */
@FragmentScope
public class EditFoodPresenter extends BasePresenter<EditFoodContract.Model, EditFoodContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public EditFoodPresenter(EditFoodContract.Model model, EditFoodContract.View rootView) {
        super(model, rootView);
    }

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

    public void loadInfo(int fragmentType) {
        if (fragmentType == SELECT_TIME_PERIOD) {
            getPeriodList();
        } else if (fragmentType == SELECT_FOOD_TYPE) {
            getSummaryList();
        }
    }

    public void deleteInfoById(int fragmentType, int id, int position) {
        Observable<BaseResult> baseResultObservable = null;
        if (fragmentType == SELECT_TIME_PERIOD) {
            baseResultObservable = mModel.deletePeriod(id);
        } else if (fragmentType == SELECT_FOOD_TYPE) {
            baseResultObservable = mModel.deleteSummary(id);
        }

        if (baseResultObservable != null) {
            deletePeriod(baseResultObservable, position);
        }
    }

    /**
     * 刪除時段
     * @param position
     */
    private void deletePeriod(Observable<BaseResult> observable, int position) {
        observable.subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("刪除中..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResult result) {
                        if (result.isSuccess()) {
                            mRootView.deleteByPosition(position);
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                    }
                });
    }

    /**
     * 獲取時段列表
     */
    private void getPeriodList() {
        mModel.getPeriodList(RestaurantInfoManager.newInstance().getBrandId())
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("獲取時段信息中..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResult result) {
                        if (result.isSuccess()) {
                            List<TimePeriodBean> timePeriodBeans = JsonUtils.parseArray(result.getData(), TimePeriodBean.class);
                            if (timePeriodBeans != null) {
                                List<FoodGroupBean> foodGroupBeans = new ArrayList<>();
                                for (TimePeriodBean timePeriodBean : timePeriodBeans) {
                                    foodGroupBeans.add(new FoodGroupBean(timePeriodBean.getId(), timePeriodBean.getPeriodName1()));
                                }
                                mRootView.loadInfoList(foodGroupBeans);
                                mRootView.setTimePeriodClick(timePeriodBeans);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                    }
                });
    }

    /**
     * 獲取餐種
     */
    private void getSummaryList() {
        mModel.getSummaryList(RestaurantInfoManager.newInstance().getRestaurantId())
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("獲取餐種信息中..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResult result) {
                        if (result.isSuccess()) {
                            List<SummaryBean> summaryBeans = JsonUtils.parseArray(result.getData(), SummaryBean.class);
                            if (summaryBeans != null) {
                                List<FoodGroupBean> foodGroupBeans = new ArrayList<>();
                                for (SummaryBean summaryBean : summaryBeans) {
                                    foodGroupBeans.add(new FoodGroupBean(summaryBean.getId(), summaryBean.getName()));
                                }
                                mRootView.loadInfoList(foodGroupBeans);
                                mRootView.setSummaryClick(summaryBeans);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                    }
                });
    }
}
