package com.rnboat.process;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.util.Log;

import com.rnboat.framework.ConfigManager;
import com.rnboat.process.services.RNBoatCoreService;
import com.rnboat.process.services.RNBoatDaemonService;

import java.util.List;


/**
 * 守护进程管理类
 */
public class RNBoatDaemonManager {

    private final static String TAG = RNBoatDaemonManager.class.getSimpleName();

    /**
     * 启动核心进程
     */
    public static void startCoreProcess(Context context) {
        Log.i(TAG, "startCoreProcess: 启动核心进程");
        Intent wakeIntent = new Intent(context, RNBoatCoreService.class);
        context.startService(wakeIntent);
    }

    public static boolean isAppRunning(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(9999);
        if (list.size() <= 0) {
            return false;
        }
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.baseActivity.getPackageName().equals(ConfigManager.APP_PACKAGE_NAME)) {
                return true;
            }
        }
        return false;
    }

    public static void startApplication(Context context) {
        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
        PackageInfo packageinfo = null;
        try {
            packageinfo = context.getPackageManager().getPackageInfo(ConfigManager.APP_PACKAGE_NAME, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageinfo == null) {
            return;
        }

        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageinfo.packageName);

        // 通过getPackageManager()的queryIntentActivities方法遍历
        List<ResolveInfo> resolveinfoList = context.getPackageManager()
                .queryIntentActivities(resolveIntent, 0);

        ResolveInfo resolveinfo = resolveinfoList.iterator().next();
        if (resolveinfo != null) {
            // packagename = 参数packname
            String packageName = resolveinfo.activityInfo.packageName;
            // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式：packagename.mainActivityname]
            String className = resolveinfo.activityInfo.name;
            // LAUNCHER Intent
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // 设置ComponentName参数1:packagename参数2:MainActivity路径
            ComponentName cn = new ComponentName(packageName, className);

            intent.setComponent(cn);
            context.startActivity(intent);
        }
    }

    public static boolean isServiceRunning(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(9999);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }

    public static void stopAllDaemonService(Context context) {
        if (RNBoatDaemonManager.isServiceRunning(context, "com.rnboat.process.services.RNBoatDaemonService")) {
            Intent closeCoreServiceIntent = new Intent();
            closeCoreServiceIntent.setAction(RNBoatCoreService.CORE_SERVICE_CLOSE_ACTION);
            context.sendBroadcast(closeCoreServiceIntent);

            Intent closeDaemonServiceIntent = new Intent();
            closeDaemonServiceIntent.setAction(RNBoatDaemonService.DAEMON_SERVICE_CLOSE_ACTION);
            context.sendBroadcast(closeDaemonServiceIntent);
        }
    }

}
