package com.base.filerecoveryrecyclebin.activity.appmanager

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.view.View
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import com.base.filerecoveryrecyclebin.adapter.AppManagerAdapter
import com.base.filerecoveryrecyclebin.ads.AdmobMaxHelper
import com.base.filerecoveryrecyclebin.bean.AppBean
import com.base.filerecoveryrecyclebin.databinding.ActivityAppManagerBinding
import com.base.filerecoveryrecyclebin.help.BaseActivity
import com.base.filerecoveryrecyclebin.utils.BarUtils
import com.base.filerecoveryrecyclebin.utils.RamUtils.ramPair
import com.base.filerecoveryrecyclebin.view.DialogViews.showExitFunctionDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


class AppManagerActivity : BaseActivity<ActivityAppManagerBinding>() {

    var uninstallTimes = 0
    override val binding: ActivityAppManagerBinding by lazy {
        ActivityAppManagerBinding.inflate(layoutInflater)
    }

    private lateinit var adapter: AppManagerAdapter


    private var ePercent = 0

    @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()
        ePercent = percent

        adapter = AppManagerAdapter(true) { pkg ->
            if (uninstallTimes % 3 == 0 && uninstallTimes > 0) {
                AdmobMaxHelper.admobMaxShowInterstitialAd(this, isLoading = false) { unInstall(pkg) }
            } else {
                unInstall(pkg)
            }
        }
        binding.rv.adapter = adapter

        initData()
    }

    private fun unInstall(pkg: String) {
        val intent = Intent(Intent.ACTION_DELETE, Uri.parse("package:${pkg}"))
        launcher.launch(intent) {
            if (!isInstalled(this, pkg)) {
                adapter.removeBean(pkg)
                uninstallTimes++
            }
        }
    }

    private fun isInstalled(context: Context, pkg: String, error: (() -> Unit)? = null): Boolean {
        return try {
            context.packageManager.getPackageInfo(pkg, 0)
            true
        } catch (e: Exception) {
            error?.invoke()
            false
        }
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            showExitFunctionDialog(this@AppManagerActivity){showAd ->
                if (showAd){
                    AdmobMaxHelper.admobMaxShowInterstitialAd(this@AppManagerActivity, isLoading = false) {
                        finishToMain()
                    }
                }else{
                    finishToMain()
                }

            }
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
    }

    @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@AppManagerActivity, 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
    }

}