package com.example.iot_controlhost.utils;

import android.content.Context;
import android.os.Environment;
import android.os.StrictMode;

import com.blankj.utilcode.util.StringUtils;
import com.example.iot_controlhost.model.net.AppVersion;
import com.example.iot_controlhost.model.net.CommonResponse;
import com.example.iot_controlhost.ui.dialog.ConfirmDialog;
import com.example.iot_controlhost.utils.global.HardwareSetting;
import com.example.iot_controlhost.utils.network.PublicNetRequest;
import com.example.iot_controlhost.utils.network.Url;
import com.example.iot_controlhost.utils.network.XHttpManager;
import com.example.iot_controlhost.utils.network.XHttpShorthand;

import org.xutils.http.RequestParams;
import org.xutils.x;

import es.dmoral.toasty.Toasty;

/**
 * App更新工具类
 *
 * @author DuanKaiji
 */
public class AppUpdateUtil {

    /**
     * 检查是否需要升级APP，以及进行升级
     *
     * @param mContext          上下文
     * @param needSilentTips    是否需要静默提示
     * @param needForceDownLoad 是否需要直接下载（不询问用户）
     */
    public static void updateAPP(Context mContext, boolean needSilentTips, boolean needForceDownLoad) {
        if (!needSilentTips) {
            DialogUtil.showLoadingDialog(mContext, "正在检测更新中");
        }
        int curVersion = MyUtil.getVersion(mContext);
        String curVersionName = MyUtil.getVersionName(mContext);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.checkAppNewVersion);
        params.addParameter("HostCode", HardwareSetting.getHostId());
        params.addParameter("VersionNumber", curVersion);
        params.addParameter("VersionName", curVersionName);
        x.http().get(params, new XHttpShorthand<AppVersion>() {
            @Override
            public void success(AppVersion model) {
                if (model.getData() != null) {
                    int server = model.getData().getVersionNumber();
                    if (server > curVersion) {
                        AppVersion.DataDTO data = model.getData();
                        if (needForceDownLoad) {
                            PublicNetRequest.downFile(mContext, data.getUrl());
                        } else {
                            new ConfirmDialog(mContext, "检测到新版本", "新版本内容：\n" + data.getVersionDescription(), () -> {
                                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                                    PublicNetRequest.downFile(mContext, data.getUrl());
                                } else {
                                    Toasty.error(mContext, "SD卡不可用，请插入SD卡").show();
                                }
                            }).show();
                        }
                        if (!needSilentTips) {
                            Toasty.success(mContext, "检测到新版本").show();
                        }
                    } else {
                        if (!needSilentTips) {
                            Toasty.success(mContext, "当前已是最新版本").show();
                        }
                    }
                } else if (!StringUtils.isEmpty(model.getMessage())) {
                    if (!needSilentTips) {
                        Toasty.success(mContext, model.getMessage()).show();
                    }
                }
            }

            @Override
            public void onSuccessError(CommonResponse data) {
                if (!needSilentTips) {
                    Toasty.success(mContext, data.getMessage()).show();
                }
            }

            @Override
            public void error(Throwable e) {
                if (!needSilentTips) {
                    Toasty.error(mContext, "检测失败：" + e.getMessage()).show();
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (!needSilentTips) {
                    DialogUtil.hideLoadingDialog();
                }
            }
        });
    }
}