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

import android.app.Application;

import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.core.restaurant.bean.BrandsBean;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.login.mvp.bean.LoginLimitBean;
import com.gingersoft.gsa.cloud.login.mvp.contract.ChooseRestaurantContract;
import com.gingersoft.gsa.cloud.login.mvp.ui.activity.LoginActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
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.List;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import okhttp3.FormBody;
import okhttp3.RequestBody;


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

    @Inject
    public ChooseRestaurantPresenter (ChooseRestaurantContract.Model model, ChooseRestaurantContract.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 getRestaurantList() {
        mModel.getRestaurantList()
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> mRootView.showLoading("獲取餐廳信息中..."))
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BrandsBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BrandsBean info) {
                        if (info != null) {
                            if(TextUtil.isNotEmptyOrNullOrUndefined(info.getMessage())){
                                mRootView.showMessage(info.getMessage());
                            }
                            mRootView.saveRestaurantListInfo(info.getData());
                        } else {
                            mRootView.saveRestaurantListInfo(null);
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.showMessage("獲取餐廳信息失敗");
                        mRootView.killMyself();
                    }
                });
    }

    /**
     * @param restaurantId 餐廳ID
     * @param isDownload   是否去下載頁面
     */
    public void getLoginLimit(int restaurantId, boolean isDownload) {
        mModel.getLoginLimit(restaurantId)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> mRootView.showLoading("獲取登錄人數中..."))
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResult s) {
                        if (s != null && s.isSuccess()) {
                            List<LoginLimitBean> loginLimitBeans = new Gson().fromJson(GsonUtils.GsonString(s.getData()), new TypeToken<List<LoginLimitBean>>() {}.getType());
//                            List<LoginLimitBean> logins = GsonUtils.GsonToList("", LoginLimitBean.class);
                            if (loginLimitBeans == null || loginLimitBeans.size() <= 0) {
                                if (isDownload) {
                                    mRootView.jumpDownloadActivity();
                                } else {
                                    mRootView.jumpMainActivity();
                                }
                            } else {
                                mRootView.showMessage("登錄人數達到上限");
                                //已達上限，彈出彈窗
                                mRootView.showLoginLimit(loginLimitBeans);
                            }
                        } else {
                            mRootView.showMessage("獲取登陸人數失敗");
                            mRootView.jumpActivity(LoginActivity.class);
                        }
                    }

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

    /**
     * 踢出用戶
     */
    public void loginOut(int userId) {
        RequestBody requestBody = new FormBody.Builder()
                .add("type", "2")
                .build();
        mModel.loginOut(userId, requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<Object>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull Object info) {
                        mRootView.kickOut();
                    }

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