package com.bbitcn.silk.ui.activity;

import android.app.Application;
import android.os.Build;
import android.os.StrictMode;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.bbitcn.silk.base.BasePresenter;
import com.bbitcn.silk.model.net.CommonResponse;
import com.bbitcn.silk.model.net.Update;
import com.bbitcn.silk.utils.DialogUtil;
import com.bbitcn.silk.utils.network.Url;
import com.bbitcn.silk.utils.network.XHttpManager;
import com.bbitcn.silk.utils.network.XHttpShorthand;
import com.blankj.utilcode.util.StringUtils;

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

/**
 * @Author DuanKaiji
 * @CreateTime 2024年3月28日 10:06:01
 */
public class UpdateActivityPresenter extends BasePresenter {
    public MutableLiveData<String> lastVersion = new MutableLiveData<>("");
    public MutableLiveData<Update.DataDTO> versionInfo = new MutableLiveData<>();

    public UpdateActivityPresenter(@NonNull Application application) {
        super(application);
        checkVersion();
    }

    public MutableLiveData<Update.DataDTO> getVersionInfo() {
        return versionInfo;
    }

    /**
     * 检查是否需要升级APP，以及进行升级
     */
    public void checkVersion() {
        showLoadingDialog("正在检测更新中");
        if (Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.getNewVersion,false);
        x.http().get(params, new XHttpShorthand<Update>() {
            @Override
            public void success(Update model) {
                if (model.getData() != null) {
                    versionInfo.setValue(model.getData());
                    lastVersion.setValue(model.getData().getVersionName());
                } else if (!StringUtils.isEmpty(model.getMsg())) {
                    errorTips(model.getMsg());
                }
            }

            @Override
            public void onSuccessError(CommonResponse data) {
                successTips(data.getMsg());
            }

            @Override
            public void error(Throwable e) {
                errorTips(e.getMessage());
            }

            @Override
            public void myFinish() {
                super.myFinish();
                DialogUtil.hideLoadingDialog();
            }
        });
    }

}
