package com.secspace.lib.common.update;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.secspace.lib.common.BuildConfig;
import com.secspace.lib.common.R;
import com.secspace.lib.common.event.OnPushMessageEvent;
import com.secspace.lib.common.event.OnPushTokenUpdateEvent;
import com.secspace.lib.common.utils.ImeiUtil;
import com.secspace.lib.common.utils.PkgManager;
import com.secspace.log.Log;
import com.skr.update.AppUpdateManager;
import com.skr.update.annotation.ApkPlatform;
import com.skr.update.annotation.AppInstallPolicy;
import com.skr.update.annotation.CheckType;
import com.skr.update.db.DbRepo;
import com.skr.update.db.entity.AppUpdateInfo;
import com.skr.update.option.PlatformUpdateOption;
import com.skr.update.option.PushOption;
import com.skr.update.option.SalesPlatformUpdateOption;
import com.skr.update.option.SinglePlatformUpdateOption;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Launcher
 *
 * @author lichuanzhi@tiankuan.net
 */
@SuppressLint("StaticFieldLeak")
public class CheckUpdateCore {

    private static final CheckUpdateCore INST = new CheckUpdateCore();
    private static final String TAG = "CheckUpdateCore";

    private Context mAppCtx;

    private CheckUpdateCore() {
    }

    public static CheckUpdateCore get() {
        return INST;
    }

    public void init(Context context) {
        mAppCtx = context.getApplicationContext();
        int[] certificates = new int[]{R.raw.tomcat_115_29_115_27};
        AppUpdateManager.get().init(context, certificates, new AppUpdateManager.OnAppUpdateListener(){

            @Override
            public boolean allowInstall(long l, String s) {
                return true;
            }

            @Override
            public void onInstall(String path, boolean isManual) {
                PkgManager.getInstance(mAppCtx).installByInstaller(path);
            }
        });
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    /**
     * push token
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onToken(OnPushTokenUpdateEvent e) {
        PushOption option = AppUpdateManager.get().getPushOption();
        if(option!=null){
            AppUpdateManager.get().uploadPushToken(e.token);
        }
    }

    /**
     * push message
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPushMessage(OnPushMessageEvent e) {
        AppUpdateManager.get().onReceivePush(e.message);
    }

    /**
     * 启用更新
     */
    public void enableUpdate() {
        Log.i(TAG, "enableUpdate");
        if (BuildConfig.AUTO_UPDATE) {
            enableAutoUpdate();
        } else {
            checkUpdate(false);
        }
    }

    /**
     * 打开自动更新
     */
    private void enableAutoUpdate() {
        int platform = BuildConfig.UPDATE_PLATFORM;
        String imei = ImeiUtil.INSTANCE.uniqueId(mAppCtx, false);
        if (TextUtils.isEmpty(imei)) {
            return;
        }
        PlatformUpdateOption option;
        if (platform == ApkPlatform.SALES) {
            option = new SalesPlatformUpdateOption.Builder()
                    .imei(imei)
                    .server(BuildConfig.UPDATE_SERVER)
                    .name(BuildConfig.UPDATE_FLAG)
                    .companyId(BuildConfig.COMPANY_ID)
                    .showDownloadDialog(true)
                    .showDownloadNotification(true)
                    .appInstallPolicy(AppInstallPolicy.SILENT_INSTALL)
                    .build();
        } else {
            option = new SinglePlatformUpdateOption.Builder()
                    .imei(imei)
                    .server(BuildConfig.UPDATE_SERVER)
                    .showDownloadDialog(true)
                    .showDownloadNotification(true)
                    .appInstallPolicy(AppInstallPolicy.SILENT_INSTALL)
                    .build();
        }
        AppUpdateManager.get().startAutoUpdate(option);
        PushOption pushOption = new PushOption.Builder()
                .imei(imei)
                .platform(platform)
                .server(BuildConfig.UPDATE_SERVER)
                .build();
        AppUpdateManager.get().enablePush(pushOption);
    }

    /**
     * 检查更新
     */
    public void checkUpdate(boolean isShowToast) {
        String imei = ImeiUtil.INSTANCE.uniqueId(mAppCtx, false);
        SalesPlatformUpdateOption option = new SalesPlatformUpdateOption.Builder()
                .imei(imei)
                .server(BuildConfig.UPDATE_SERVER)
                .name(BuildConfig.UPDATE_FLAG)
                .companyId(BuildConfig.COMPANY_ID)
                .showDownloadDialog(false)
                .showDownloadNotification(false)
                .appInstallPolicy(AppInstallPolicy.SILENT_INSTALL)
                .build();
        AppUpdateManager.get().checkUpdate(option, isShowToast);
    }

    /**
     * 是否有检查更新
     */
    public boolean hasManualUpdate() {
        int versionCode = 0;
        try {
            PackageInfo pi = mAppCtx.getPackageManager().getPackageInfo(mAppCtx.getPackageName(), 0);
            if (pi != null) {
                versionCode = pi.versionCode;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        AppUpdateInfo info = DbRepo.get().queryUncompletedAppUpdateByCheckType(CheckType.MANUAL);
        return info != null && info.getVersionCode() > versionCode;
    }
}
