package com.miraclegarden.smsmessage.mmp;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

/**
 * 记录 TNG 进程内 Hook 心跳，用于判断是否挂上最新模块。
 */
public final class MmpHookStatus {

    private static final String PREF = "mmp_hook_status";
    private static volatile int sLiveCode;
    private static volatile String sLiveName = "";
    private static volatile long sLiveAt;
    private static volatile String sHostPkg = "";

    private MmpHookStatus() {
    }

    public static void noteAlive(Context context, int versionCode, String versionName,
                                 String hostPackage) {
        sLiveCode = versionCode;
        sLiveName = versionName != null ? versionName : "";
        sLiveAt = System.currentTimeMillis();
        sHostPkg = hostPackage != null ? hostPackage : "";
        if (context == null) {
            return;
        }
        prefs(context).edit()
                .putInt("live_code", sLiveCode)
                .putString("live_name", sLiveName)
                .putLong("live_at", sLiveAt)
                .putString("host_pkg", sHostPkg)
                .apply();
    }

    public static void ensureLoaded(Context context) {
        if (sLiveAt > 0 || context == null) {
            return;
        }
        SharedPreferences sp = prefs(context);
        sLiveCode = sp.getInt("live_code", 0);
        sLiveName = sp.getString("live_name", "");
        sLiveAt = sp.getLong("live_at", 0L);
        sHostPkg = sp.getString("host_pkg", "");
    }

    public static long lastAliveAt(Context context) {
        ensureLoaded(context);
        return sLiveAt;
    }

    public static int liveVersionCode(Context context) {
        ensureLoaded(context);
        return sLiveCode;
    }

    public static String liveVersionName(Context context) {
        ensureLoaded(context);
        return sLiveName != null ? sLiveName : "";
    }

    public static int installedVersionCode(Context context) {
        if (context == null) {
            return 0;
        }
        try {
            PackageInfo pi = context.getPackageManager()
                    .getPackageInfo(MmpModuleInfo.XPOSED_PACKAGE, 0);
            return pi != null ? pi.versionCode : 0;
        } catch (PackageManager.NameNotFoundException e) {
            return 0;
        }
    }

    public static String installedVersionName(Context context) {
        if (context == null) {
            return "";
        }
        try {
            PackageInfo pi = context.getPackageManager()
                    .getPackageInfo(MmpModuleInfo.XPOSED_PACKAGE, 0);
            return pi != null && pi.versionName != null ? pi.versionName : "";
        } catch (PackageManager.NameNotFoundException e) {
            return "";
        }
    }

    /**
     * @return 人类可读模块状态
     */
    public static String describe(Context context) {
        ensureLoaded(context);
        int installed = installedVersionCode(context);
        String installedName = installedVersionName(context);
        if (installed <= 0) {
            return "模块APK：未安装";
        }
        String apkPart = "模块APK：" + (TextUtils.isEmpty(installedName)
                ? String.valueOf(installed) : installedName);
        boolean apkLatest = installed >= MmpModuleInfo.EXPECTED_VERSION_CODE;
        if (!apkLatest) {
            apkPart += "(旧，期望" + MmpModuleInfo.EXPECTED_VERSION_NAME + ")";
        }

        long age = sLiveAt > 0 ? System.currentTimeMillis() - sLiveAt : -1L;
        String livePart;
        if (age < 0) {
            livePart = "运行中：未检测到（请强停再开 TNG）";
        } else if (age > 3 * 60_000L) {
            livePart = "运行中：心跳偏旧(" + (age / 60_000L) + "分钟前 "
                    + (TextUtils.isEmpty(sLiveName) ? sLiveCode : sLiveName) + ")";
        } else if (sLiveCode >= MmpModuleInfo.EXPECTED_VERSION_CODE) {
            livePart = "运行中：最新(" + (TextUtils.isEmpty(sLiveName) ? sLiveCode : sLiveName) + ")";
        } else if (sLiveCode > 0) {
            livePart = "运行中：旧版(" + (TextUtils.isEmpty(sLiveName) ? sLiveCode : sLiveName)
                    + "，期望" + MmpModuleInfo.EXPECTED_VERSION_NAME + ")";
        } else {
            livePart = "运行中：未知";
        }
        return apkPart + "  ·  " + livePart;
    }

    public static boolean isLiveLatest(Context context) {
        ensureLoaded(context);
        long age = sLiveAt > 0 ? System.currentTimeMillis() - sLiveAt : -1L;
        return age >= 0 && age <= 3 * 60_000L && sLiveCode >= MmpModuleInfo.EXPECTED_VERSION_CODE;
    }

    private static SharedPreferences prefs(Context context) {
        return context.getApplicationContext().getSharedPreferences(PREF, Context.MODE_PRIVATE);
    }
}
