package com.gh.common.util

import android.content.Context
import android.content.pm.ApplicationInfo
import com.gh.common.constant.Config
import com.gh.gamecenter.feature.entity.SettingsEntity
import com.halo.assistant.HaloApp

object PackageHelper {

    // 评论黑名单包名列表，避免用户安装了 Xposed Installer 这样的工具，也能在包含该安装包的游戏详情页评论
    var commentPackageNameBlackList = arrayListOf<String>()

    // 关闭下载的包列表
    var downloadPackageNameBlackList = arrayListOf<String>()

    // 本地已安装的包去掉关闭下载的包后的列表
    var validLocalPackageNameSet = hashSetOf<String>()

    // 游戏包名匹配列表
    var relatedPackageList = arrayListOf<SettingsEntity.GameWithPackages>()

    // 本地已安装包的列表
    var localPackageNameSet = hashSetOf<String>()
        get() {
            return if (field.isEmpty()) {
                field = getAllPackageName(HaloApp.getInstance().application)
                field
            } else {
                field
            }
        }

    @JvmStatic
    fun refreshLocalPackageList() {
        localPackageNameSet = getAllPackageName(HaloApp.getInstance().application)
        updateValidPackageNameList()
    }

    @JvmStatic
    fun initList() {
        Config.getSettings()?.gameCommentBlackList?.let {
            commentPackageNameBlackList = ArrayList(it)
        }
        Config.getSettings()?.gameDownloadBlackList?.let {
            downloadPackageNameBlackList = ArrayList(it)
        }
        Config.getSettings()?.gamePackageMatch?.let {
            relatedPackageList = ArrayList(it)
        }

        Config.getSettings()?.gameDownloadBlackList
        updateValidPackageNameList()
    }

    private fun updateValidPackageNameList() {
        validLocalPackageNameSet =
            localPackageNameSet.filterNot { p -> downloadPackageNameBlackList.contains(p) }.toHashSet()
    }

    /*
     * 获取所有已安装的软件的包名、版本(非系统应用)
     */
    private fun getAllPackageName(context: Context): HashSet<String> {
        val set = HashSet<String>()
        return try {
            val packageInfos = PackageUtils.getInstalledPackages(context, 0)
            for (packageInfo in packageInfos) {
                if (packageInfo.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM == 0) {
                    if (context.packageName != packageInfo.packageName) {
                        set.add(packageInfo.packageName)
                    }
                }
            }
            set
        } catch (e: Exception) {
            e.printStackTrace()
            set
        }
    }

}