package com.miraclegarden.smsmessage.mmp;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 检测 / 拉起 TNG，供领取台「自动检测」「杀掉后自动打开」使用。
 */
public final class TngProcessHelper {

    private static final String TAG = "TngProcessHelper";
    public static final String TNG_PACKAGE = "my.com.tngdigital.ewallet";

    private TngProcessHelper() {
    }

    public static boolean isRunning(Context context) {
        if (context == null) {
            return false;
        }
        if (pidofAlive()) {
            return true;
        }
        try {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            if (am == null) {
                return false;
            }
            List<ActivityManager.RunningAppProcessInfo> list = am.getRunningAppProcesses();
            if (list == null) {
                return false;
            }
            for (ActivityManager.RunningAppProcessInfo info : list) {
                if (info == null || TextUtils.isEmpty(info.processName)) {
                    continue;
                }
                if (info.processName.equals(TNG_PACKAGE)
                        || info.processName.startsWith(TNG_PACKAGE + ":")) {
                    return true;
                }
            }
        } catch (Exception e) {
            Log.w(TAG, "running check fail", e);
        }
        return false;
    }

    private static boolean pidofAlive() {
        String out = shell("pidof " + TNG_PACKAGE);
        if (TextUtils.isEmpty(out)) {
            out = shell("su -c pidof " + TNG_PACKAGE);
        }
        return !TextUtils.isEmpty(out) && out.trim().matches(".*\\d.*");
    }

    private static String shell(String cmd) {
        Process p = null;
        try {
            p = Runtime.getRuntime().exec(new String[]{"sh", "-c", cmd});
            if (!p.waitFor(2, TimeUnit.SECONDS)) {
                p.destroy();
                return "";
            }
            StringBuilder sb = new StringBuilder();
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line).append('\n');
                }
            }
            return sb.toString().trim();
        } catch (Exception e) {
            return "";
        } finally {
            if (p != null) {
                p.destroy();
            }
        }
    }

    /** @return true 已发出打开 Intent */
    public static boolean launch(Context context) {
        if (context == null) {
            return false;
        }
        try {
            PackageManager pm = context.getPackageManager();
            Intent intent = pm.getLaunchIntentForPackage(TNG_PACKAGE);
            if (intent == null) {
                Log.w(TAG, "no launch intent for TNG");
                return false;
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            context.startActivity(intent);
            Log.i(TAG, "launched TNG");
            return true;
        } catch (Exception e) {
            Log.e(TAG, "launch TNG fail", e);
            return false;
        }
    }
}
