package com.android.common.utils;

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

import com.orhanobut.logger.Logger;

import java.lang.reflect.Method;

/**
 * @author 910040
 * @version 1.0
 * @date 2018/11/8
 */
public class AppUtils {

    private static final int DEFAULT_APP_VERSION = 1;

    private static final String GET_FOREGROUND_ACTIVITY_CMD = "dumpsys activity | grep \"mResumedActivity:\" ";

    /**
     * Context对象
     */
    private static Context sAppContext;

    /**
     * 取得Context对象
     * PS:第一次必须在主线程调用才能获取到context对象
     *
     * @return Context
     */
    public static Context getAppContext() {
        if (sAppContext == null) {
            synchronized (AppUtils.class) {
                if (sAppContext == null) {
                    try {
                        Class<?> activityThread = Class.forName("android.app.ActivityThread");
                        Method method = activityThread.getMethod("currentActivityThread");
                        //获取currentActivityThread 对象
                        Object currentActivityThread = method.invoke(activityThread);
                        Method method2 = currentActivityThread.getClass().getMethod("getApplication");
                        //获取 Context对象
                        sAppContext = (Context) method2.invoke(currentActivityThread);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return sAppContext;
    }

    public static void setAppContext(Context appContext){
        sAppContext = appContext;
    }


    /**
     * 获取当前应用版本号， 默认1
     * @return versionCode
     */
    public static int getAppVersionCode() {
        try {
            getAppContext();
            PackageInfo packageInfo = sAppContext.getPackageManager().getPackageInfo(sAppContext.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            Logger.e(e, "getAppViersion exception");
        }
        return DEFAULT_APP_VERSION;
    }


    /**
     * 获取前台进程包名
     * @return
     */
    public static String getForegroundPackageName() {
        ShellUtils.CommandResult result = ShellUtils.execCmd(GET_FOREGROUND_ACTIVITY_CMD, false);
        if (!TextUtils.isEmpty(result.successMsg)) {
            String[] results = result.successMsg.trim().split("\\s+");
            if (results.length > 4){
                return results[3].split("/")[0];
            }
        }
        return null;
    }

}
