package com.simplecleaner.app.ui.appuninstall

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import com.simplecleaner.app.bean.AppInfoBean
import com.simplecleaner.app.utils.LogEx
import java.io.File

object AppInfoUtils {

    private val TAG = "AppInfoUtils"

    @SuppressLint("QueryPermissionsNeeded")
    fun getAppInfo(context: Context): ArrayList<AppInfoBean> {
        val packageManager: PackageManager = context.packageManager
        val apps = packageManager.getInstalledApplications(PackageManager.GET_META_DATA)

        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val memoryInfo = ActivityManager.MemoryInfo()
        activityManager.getMemoryInfo(memoryInfo)

        val list = arrayListOf<AppInfoBean>()

        for (app in apps) {
            // 过滤掉系统应用和自身应用
            if ((app.flags and ApplicationInfo.FLAG_SYSTEM) == 0 && app.packageName != context.packageName) {
                try {
                    val packageName = app.packageName

                    //app名称
                    val appName = packageManager.getApplicationLabel(app).toString()

                    // 获取app图标
                    val appIcon = packageManager.getApplicationIcon(app)

                    // 获取安装时间
                    val installTime = packageManager.getPackageInfo(packageName, 0).firstInstallTime

                    // 获取储存大小
                    val storageSize = getStorageSize(context, packageName)

                    list.add(AppInfoBean(packageName, appName, appIcon, installTime, storageSize))
                    LogEx.logDebug(TAG, "appName=$appName appIcon=$appIcon installTime=$installTime storageSize=$storageSize")

                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
        return list
    }


    private fun getStorageSize(context: Context, packageName: String): Long {
        val pm = context.packageManager
        val appInfo = pm.getApplicationInfo(packageName, 0)
        val appDir = File(appInfo.dataDir) // 获取应用的数据目录
        val apkFile = File(appInfo.sourceDir) // 获取APK文件路径

        val appDirSize = getDirectorySize(appDir)
        val apkFileSize = apkFile.length()

        return appDirSize + apkFileSize
    }


    private fun getDirectorySize(directory: File): Long {
        var totalSize = 0L
        val files = directory.listFiles() ?: return 0L
        for (file in files) {
            if (file.isDirectory) {
                totalSize += getDirectorySize(file)
            } else {
                totalSize += file.length()
            }
        }
        return totalSize
    }


}