package com.base.browserwhite.ui.activity.appprocess

import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.base.browserwhite.bean.AppBean
import com.base.browserwhite.databinding.ActivityAppProcessBinding
import com.base.browserwhite.ui.activity.BaseActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class AppProcessActivity : BaseActivity<ActivityAppProcessBinding>() {

    override val binding: ActivityAppProcessBinding by lazy {
        ActivityAppProcessBinding.inflate(layoutInflater)
    }
    private lateinit var adapter: AppBeanAdapter


    override fun initView() {
        adapter = AppBeanAdapter()
    }


    @SuppressLint("QueryPermissionsNeeded")
    private fun initData() = lifecycleScope.launch(Dispatchers.IO) {
        val pm = packageManager
        val packages = pm.getInstalledPackages(0)
        val list = arrayListOf<AppBean>()

        packages.forEach { app ->

            if (isLaunchApp(this@AppProcessActivity, app)) {

                val appBean = AppBean(
                    app.applicationInfo.loadIcon(pm),
                    app.applicationInfo.loadLabel(pm).toString(),
                    app.applicationInfo.packageName
                )
                list.add(appBean)
            }
        }
        launch(Dispatchers.Main) {
            binding.progressBarLoading.visibility = View.GONE
        }
    }

    private fun isLaunchApp(context: Context, app: PackageInfo, filterSystem: Boolean = true): Boolean {

        val flagSystem = (app.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM) < 1
        val flag = if (filterSystem) flagSystem else true

        return flag && app.applicationInfo.packageName != context.packageName
    }
}