package com.base.datarecovery.activity.appprocess

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.graphics.Color
import android.net.Uri
import android.provider.Settings
import android.view.View
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.adapter.AppManagerAdapter
import com.base.datarecovery.ads.AdmobMaxHelper
import com.base.datarecovery.bean.AppBean
import com.base.datarecovery.databinding.ActivityAppManagerBinding
import com.base.datarecovery.help.BaseActivity
import com.base.datarecovery.help.KotlinExt.toFormatSize
import com.base.datarecovery.utils.BarUtils
import com.base.datarecovery.utils.RamUtils.ramPair
import com.base.datarecovery.view.DialogViews.showExitFunctionDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


class AppProcessActivity : BaseActivity<ActivityAppManagerBinding>() {

    override val binding: ActivityAppManagerBinding by lazy {
        ActivityAppManagerBinding.inflate(layoutInflater)
    }

    private lateinit var adapter: AppManagerAdapter


    @SuppressLint("SetTextI18n")
    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())

        val ramPair = ramPair()
        val percent = ((ramPair.first.toFloat() / ramPair.second.toFloat()) * 100).toInt()
        binding.tvPercent.text = percent.toString()
        binding.pbRam.progress = percent
        binding.tvSize.text = "${ramPair.first.toFormatSize()}/${ramPair.second.toFormatSize()}"

        adapter = AppManagerAdapter { pkg ->
            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            val uri = Uri.fromParts("package", pkg, null) // 替换为需要跳转的应用包名
            intent.setData(uri)
            startActivity(intent)
        }
        binding.rv.adapter = adapter

        initData()
    }

    override fun initListener() {
        super.initListener()
        binding.flFanhui.setOnClickListener {
            showExitFunctionDialog { showAd ->
                if (showAd) {
                    AdmobMaxHelper.admobMaxShowInterstitialAd(this) {
                        finishToMain()
                    }
                } else {
                    finishToMain()
                }
            }
        }
    }

    @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.pbLoading.visibility = View.GONE
            adapter.setData(list)
        }
    }

    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
    }

}