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

import android.app.Application;

import com.gingersoft.gsa.cloud.account.restaurant.ResturantInfoManager;
import com.gingersoft.gsa.cloud.app.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.base.utils.CollectionUtils;
import com.gingersoft.gsa.cloud.base.utils.JsonUtils;
import com.gingersoft.gsa.cloud.base.utils.RestaurantExpandInfoUtils;
import com.gingersoft.gsa.cloud.base.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.database.bean.ExpandInfo;
import com.gingersoft.gsa.cloud.database.utils.ExpandInfoDaoUtils;
import com.gingersoft.gsa.cloud.main.mvp.contract.ExpandListContract;
import com.jess.arms.di.scope.ActivityScope;
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.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import okhttp3.MediaType;
import okhttp3.RequestBody;


@ActivityScope
public class ExpandListPresenter extends BasePresenter<ExpandListContract.Model, ExpandListContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private List<ExpandInfo> originalDate;

    @Inject
    public ExpandListPresenter(ExpandListContract.Model model, ExpandListContract.View rootView) {
        super(model, rootView);
        originalDate = new ArrayList<>();
    }

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

    public void getExpandInfoList() {
        mModel.getExpandList(ResturantInfoManager.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()) {
                            if (result.getData() != null) {
                                List<ExpandInfo> expandInfoList = JsonUtils.parseArray(result.getData(), ExpandInfo.class);
                                if (expandInfoList != null) {
                                    originalDate = CollectionUtils.deepCopy(expandInfoList);
                                    mRootView.loadExpandList(expandInfoList);
                                } else {
                                    if (TextUtil.isNotEmptyOrNullOrUndefined(result.getErrMsg())) {
                                        mRootView.showMessage(result.getErrMsg());
                                    } else {
                                        mRootView.showMessage("數據獲取失敗");
                                    }
                                }
                            } else {
                                if (TextUtil.isNotEmptyOrNullOrUndefined(result.getErrMsg())) {
                                    mRootView.showMessage(result.getErrMsg());
                                } else {
                                    mRootView.showMessage("數據獲取失敗");
                                }
                            }
                        }
                    }
                });
    }


    public void updateExpandInfo(List<ExpandInfo> data) {
        List<ExpandInfo> changeData = new ArrayList<>();
        if (originalDate != null) {
            for (ExpandInfo expandInfo : data) {
                if (!originalDate.contains(expandInfo)) {
                    //改變了
                    changeData.add(expandInfo);
                }
            }
        }
        if (changeData.size() <= 0) {
            mRootView.killMyself();
            return;
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(changeData));
        mModel.updateExpandInfo(requestBody)
                .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 (TextUtil.isNotEmptyOrNullOrUndefined(result.getErrMsg())) {
                            mRootView.showMessage(result.getErrMsg());
                        }
                        if (result.isSuccess()) {
                            mRootView.showMessage("保存成功");
                            ExpandInfoDaoUtils expandInfoDaoUtils = new ExpandInfoDaoUtils(GsaCloudApplication.getAppContext());
                            for (ExpandInfo expandInfo : data) {
                                expandInfoDaoUtils.updateExpandInfo(expandInfo);
                            }
                            RestaurantExpandInfoUtils.setCommonExpandInfo(data);
                            mRootView.killMyself();
                        }
                    }
                });
    }

}
