package com.tenlionsoft.baselib.core.network.update.utils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;

import com.tenlionsoft.baselib.utils.LogUtils;

import java.util.List;

public class AppUtils {

    /**
     * 获取当前应用的版本号
     *
     * @param mContext context
     * @return 版本号
     */
    public static int getVersionCode(Context mContext) {
        if (mContext != null) {
            try {
                return mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
            } catch (PackageManager.NameNotFoundException ignored) {
            }
        }
        return 0;
    }

    /**
     * 获取当前应用的版本名称
     *
     * @param mContext context
     * @return 版本名称
     */
    public static String getVersionName(Context mContext) {
        if (mContext != null) {
            try {
                return mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionName;
            } catch (PackageManager.NameNotFoundException ignored) {
            }
        }

        return "";
    }

    public static boolean isBackground(Context ctx) {
        Intent intent = new Intent();
        intent.setClassName(ctx, "com.tengshisoft.chatmodule.activity.ChatActivity");
        ComponentName cmpName = intent.resolveActivity(ctx.getPackageManager());
        boolean flag = false;
        if (cmpName != null) {
            ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(10);
            if (!tasks.isEmpty()) {
                for (ActivityManager.RunningTaskInfo taskInfo : tasks) {
                    if (taskInfo.topActivity.equals(cmpName)) {
                        flag = true;
                        break;
                    }
                }
            }
        }
        return flag;
    }
}
