package com.fxy.common;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.widget.TextView;

import com.fxy.R;
import com.fxy.base.StorageApplication;
import com.fxy.baselibrary.util.DateUtil;
import com.fxy.baselibrary.util.JsonUtil;
import com.fxy.baselibrary.views.MarqueeTextView;
import com.fxy.bean.ActionBean;
import com.fxy.bean.UpdateModel;
import com.fxy.constant.SPCache;
import com.fxy.net.MyDialogCallback;
import com.fxy.net.Urls;
import com.fxy.utils.AllDialogShowStrategy;
import com.lzy.okgo.OkGo;

import org.lzh.framework.updatepluginlib.UpdateBuilder;
import org.lzh.framework.updatepluginlib.base.UpdateParser;
import org.lzh.framework.updatepluginlib.model.Update;

import java.util.UUID;

/**
 * 本版升级共用基础类
 */
public class VersionUpgrades {
    private final Context mContext;
    private int currentVersionCode = 0;
    private String currentVersionName="";
    private String currentVersionContent="";
    private String firstInstallTime="";
    private String lastUpdateTime="";

    private MarqueeTextView mtVersionName;
    private TextView tvUpdateContent;

    public VersionUpgrades(Context context){
        mContext = context;
        getVersionCode();
    }

    public String getCurrentVersionName(){
        return currentVersionName;
    }
    public String getCurrentVersionContent(){
        return currentVersionContent;
    }
    public String getLastUpdateTime(){
        return lastUpdateTime;
    }
    //获取当前本版号
    private void getVersionCode() {
        try {
            PackageManager manager = mContext.getPackageManager();
            PackageInfo packageInfo = manager.getPackageInfo(mContext.getPackageName(), 0);
            //XLog.e(packageInfo);
            currentVersionCode = packageInfo.versionCode;
            currentVersionName = packageInfo.versionName;
            //应用装时间
            firstInstallTime = DateUtil.utc2Local(DateUtil.getStandardMillon(packageInfo.firstInstallTime), DateUtil.FORMAT_YMDHMS);
            //应用最后一次更新时间
            lastUpdateTime = DateUtil.utc2Local(DateUtil.getStandardMillon(packageInfo.lastUpdateTime), DateUtil.FORMAT_YMDHMS);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    //检查设置
    public void checkUpgrades(MarqueeTextView marqueeTextView, TextView textView){
        mtVersionName = marqueeTextView;
        tvUpdateContent = textView;
        checkUpgrades();
    }
    //升级本版
    public void checkUpgrades(){
        OkGo.<String>get(Urls.getVersionUpdate(mContext) + "?v=" + UUID.randomUUID().toString())
                .execute(new MyDialogCallback(mContext, false, false) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                        //super.onSuccess(response);
                        try {
                            ActionBean bean = JsonUtil.getObject(response.body().toString(), ActionBean.class);
                            if (bean.code == 1) {
                                final UpdateModel updateModel = JsonUtil.getObject(bean.data, UpdateModel.class);
                                boolean isNewVersion = updateModel.getVersionCode() > currentVersionCode;

                                //设置缓存获取
                                SPCache sp = SPCache.getInstance(mContext);
                                if (updateModel.getVersionCode()==currentVersionCode){
                                    currentVersionContent = updateModel.getUpdateContent();
                                    currentVersionName = String.format("%s(%s)",currentVersionName,mContext.getString(R.string.str_latest_version));
                                    sp.setVersion(currentVersionContent);
                                }else if (currentVersionCode > updateModel.getVersionCode()){
                                    //开发版
                                    currentVersionName = mContext.getString(R.string.str_version);
                                    currentVersionContent = mContext.getString(R.string.str_updated_details);
                                    sp.setVersion(currentVersionContent);
                                }

                                //判断是否需要更新页面信息
                                if (mtVersionName!=null && tvUpdateContent!=null){
                                    try {
                                        tvUpdateContent.setText(currentVersionContent);
                                        mtVersionName.setText(currentVersionName);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                                if (isNewVersion){
                                    UpdateBuilder updateBuilder = UpdateBuilder.create();
                                    updateBuilder.getConfig().setUrl(Urls.getVersionUpdate(mContext) + "?v=" + UUID.randomUUID().toString());
                                    updateBuilder.setUpdateParser(new UpdateParser() {
                                        @Override
                                        public Update parse(String response) throws Exception {
                                            Update update = new Update();
                                            update.setForced(updateModel.isForced());
                                            update.setIgnore(updateModel.isIgnore());
                                            update.setUpdateContent(updateModel.getUpdateContent());
                                            update.setUpdateUrl(updateModel.getUpdateUrl() + "?v=" + UUID.randomUUID().toString());
                                            update.setVersionCode(updateModel.getVersionCode());
                                            update.setVersionName(updateModel.getVersionName());
                                            return update;
                                        }
                                    });
                                    StorageApplication.context.isShowUpdateToast = true;
                                    updateBuilder.setUpdateStrategy(new AllDialogShowStrategy()).check();
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });
    }
}
