package com.miraclegarden.smsmessage;

/**
 * **********************
 *
 * @Author bug machine
 * 创建时间： 2026/3/20 15:30
 * 用途
 * **********************
 */
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class AppListUtil {

    // 获取 所有已安装APP
    public static ArrayList<AppInfo> getAllInstalledApps(Context context) {
        ArrayList<AppInfo> list = new ArrayList<>();
        PackageManager pm = context.getPackageManager();

        // 获取全部应用
        List<ApplicationInfo> apps = pm.getInstalledApplications(0);
        Log.i("多少条数据","多少条数据："+apps.size());
        for (ApplicationInfo info : apps) {
            // 只获取有桌面图标的应用（可去掉，获取全部）
            if (pm.getLaunchIntentForPackage(info.packageName) != null) {
                String name = info.loadLabel(pm).toString();
                String pkg = info.packageName;
                Drawable icon = info.loadIcon(pm);
                boolean isSystem = (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;

                list.add(new AppInfo(name, pkg, icon));
            }
        }
        return list;
    }

    // 只获取 第三方APP（排除系统APP）
    public static ArrayList<AppInfo> getThirdPartyApps(Context context) {
        ArrayList<AppInfo> list = new ArrayList<>();
        PackageManager pm = context.getPackageManager();
        List<ApplicationInfo> apps = pm.getInstalledApplications(0);

        for (ApplicationInfo info : apps) {
            // 非系统APP + 有启动图标
            if ((info.flags & ApplicationInfo.FLAG_SYSTEM) == 0
                    && pm.getLaunchIntentForPackage(info.packageName) != null) {

                list.add(new AppInfo(
                        info.loadLabel(pm).toString(),
                        info.packageName,
                        info.loadIcon(pm)
                ));
            }
        }
        return list;
    }


    /**
     * 判断某个包名是否已安装，并返回应用信息
     * @param context 上下文
     * @param packageName 指定包名
     * @return null = 未安装 / 无权限 / 找不到
     */
    public static AppInfo getAppByPackageName(Context context, String packageName) {
        try {
            PackageManager pm = context.getPackageManager();

            // ✅ 关键：直接查询指定包名（不会被系统限制）
            PackageInfo packageInfo = pm.getPackageInfo(packageName, 0);
            ApplicationInfo appInfo = packageInfo.applicationInfo;

            String appName = appInfo.loadLabel(pm).toString();
            Drawable icon = appInfo.loadIcon(pm);

            return new AppInfo(appName, packageName, icon);

        } catch (PackageManager.NameNotFoundException e) {
            // 没安装
            return null;
        }
    }
}
