package com.base.browserwhite.ui.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.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.activity.addCallback
import androidx.lifecycle.lifecycleScope
import com.base.browserwhite.ads.AdmobMaxHelper
import com.base.browserwhite.bean.AppBean
import com.base.browserwhite.bean.ConstObject.APP_PROCESS
import com.base.browserwhite.databinding.ActivityAppProcessBinding
import com.base.browserwhite.ui.activity.BaseActivity
import com.base.browserwhite.ui.activity.result.ResultActivity
import com.base.browserwhite.utils.BarUtils
import com.base.browserwhite.utils.KotlinExt.toFormatSize
import com.base.browserwhite.utils.RamUtils.ramPair
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlin.random.Random


class AppProcessActivity : BaseActivity<ActivityAppProcessBinding>() {

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


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

        adapter = AppBeanAdapter()
        adapter.stopAction = { 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

        val ramPair = ramPair()
        val percent = ((ramPair.first.toFloat() / ramPair.second.toFloat()) * 100).toInt()
        binding.progressBar.progress = percent
        binding.tvPercent.text = percent.toString()
        binding.tvRamRate.text = ramPair.first.toFormatSize() + " / " + ramPair.second.toFormatSize()

        initData()
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            AdmobMaxHelper.admobMaxShowInterstitialAd(this@AppProcessActivity, false) {
                finishToMain()
            }
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }

        binding.tvBtn.setOnClickListener {
            AdmobMaxHelper.admobMaxShowInterstitialAd(this@AppProcessActivity, false) {
                startActivity(Intent(this, ResultActivity::class.java).apply {
                    putExtra("from", APP_PROCESS)
                })
                finish()
            }

        }
    }


    @SuppressLint("QueryPermissionsNeeded")
    private fun initData() = lifecycleScope.launch(Dispatchers.IO) {
        val pm = packageManager
        val packages = pm.getInstalledPackages(0)
        val list = arrayListOf<AppBean>()
        var totalCount = 0
        var backAppCount = 0
        packages.forEachIndexed { index, packageInfo ->

            if (isLaunchApp(this@AppProcessActivity, packageInfo)) {
                totalCount++

                if (index % 2 == 0 && Random.nextBoolean()) {
                    val appBean = AppBean(
                        packageInfo.applicationInfo.loadIcon(pm),
                        packageInfo.applicationInfo.loadLabel(pm).toString(),
                        packageInfo.applicationInfo.packageName
                    )
                    list.add(appBean)
                    backAppCount++
                }

            }
        }
        launch(Dispatchers.Main) {
            binding.progressBarLoading.visibility = View.GONE
            adapter.submitList(list)

            val text = "$backAppCount/$totalCount"
            val spannableString = SpannableString(text)

            val start = text.indexOf("$backAppCount")
            val end = start + "$backAppCount".length
            val colorSpan = ForegroundColorSpan(Color.parseColor("#0672EE"))
            spannableString.setSpan(colorSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            binding.tvRate.text = spannableString.toString()
        }
    }

    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
    }

//    fun test() {
//        val am = getSystemService(ACTIVITY_SERVICE) as ActivityManager
//        val services = am.getRunningServices(Int.MAX_VALUE)
//        for (service in services) {
//            val packageName = service.service.packageName
//            // 检查packageName是否是你关心的应用程序
//            LogEx.logDebug(TAG, "packageName=$packageName")
//        }
//    }
}