package com.base.pdfviewerscannerwhite.ui.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 com.base.pdfviewerscannerwhite.ads.AdmobHelper
import com.base.pdfviewerscannerwhite.ads.admob.AdmobInterstitialUtils
import com.base.pdfviewerscannerwhite.bean.AppBean
import com.base.pdfviewerscannerwhite.bean.ConstObject
import com.base.pdfviewerscannerwhite.databinding.ActivityAppProcessBinding
import com.base.pdfviewerscannerwhite.helper.BaseActivity
import com.base.pdfviewerscannerwhite.ui.result.ResultActivity
import com.base.pdfviewerscannerwhite.utils.AppPreferences
import com.base.pdfviewerscannerwhite.utils.BarUtils
import com.base.pdfviewerscannerwhite.utils.KotlinExt.toFormatSize
import com.base.pdfviewerscannerwhite.utils.RamUtils.ramPair
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()

        AppPreferences.getInstance().put("last_process_use_time", System.currentTimeMillis())
        initDataUI()
    }

    private fun initDataUI() {
        binding.progressBarLoading.visibility = View.GONE
        adapter.submitList(appList)

        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()
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            if (AdmobHelper.isBackShowAd()) {
                AdmobInterstitialUtils.showInterstitialAd(this@AppProcessActivity) {
                    finishToMain()
                }
            } else {
                finishToMain()
            }
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }

        binding.tvBtn.setOnClickListener {
            if (AdmobHelper.isBackShowAd()) {
                AdmobInterstitialUtils.showInterstitialAd(this) {
                    startActivity(Intent(this, ResultActivity::class.java).apply {
                        putExtra("from", ConstObject.FUNCTION_APP_PROCESS)
                    })
                    finish()
                }
            } else {
                startActivity(Intent(this, ResultActivity::class.java).apply {
                    putExtra("from", ConstObject.FUNCTION_APP_PROCESS)
                })
                finish()
            }
        }
    }

    companion object {
        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
        }

        @SuppressLint("QueryPermissionsNeeded")
        fun fastGetAppIcon(context: Context): List<PackageInfo> {
            val pm = context.packageManager
            val packages = pm.getInstalledPackages(0).filter { isLaunchApp(context, it) }
            return packages
        }

        private var totalCount = 0
        private var backAppCount = 0
        private val appList = arrayListOf<AppBean>()

        @SuppressLint("QueryPermissionsNeeded")
        fun initData(
            context: Context,
        ) {
            val pm = context.packageManager
            val packages = pm.getInstalledPackages(0)
            appList.clear()

            packages.forEachIndexed { index, packageInfo ->

                if (isLaunchApp(context, packageInfo)) {
                    totalCount++

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

                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        appList.clear()
    }


}