package com.base.scanqrclear.luma

import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.activity.addCallback
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.base.scanqrclear.R
import com.base.scanqrclear.bean.AppInfoBean
import com.base.scanqrclear.databinding.ActivityAppProcessBinding
import com.base.scanqrclear.luma.DialogHelps.showExitDialog
import com.base.scanqrclear.luma.StatusBarHelps.immersiveStatusBar
import com.base.scanqrclear.utils.AnimationHelps
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class AppProcessActivity : BaseActivity2() {

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, AppProcessActivity::class.java)
            context.startActivity(intent)
        }
    }

    private val binding by lazy(LazyThreadSafetyMode.NONE) {
        ActivityAppProcessBinding.inflate(layoutInflater)
    }

    private lateinit var adapter: AppProcessAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        initView()
        initData()
        showAnimationAd(LottieType.APP_PROCESS) {
            AnimationHelps.progress(binding.pbProcess, end = binding.pbProcess.progress)
            immersiveStatusBar(this, getColor(R.color.white),true)
        }
        onBackPressedDispatcher.addCallback {
            val title = getString(R.string.exit_app_process)
            val content1 = getString(R.string.exit_app_process_content1)
            val content2 = getString(R.string.exit_app_process_content2)
            val size = adapter.itemCount
            val text = "$content1 $size $content2"
            val colorStartIndex = text.indexOf(size.toString())
            val colorEndIndex = colorStartIndex + size.toString().length
            val spannableString = SpannableString(text)
            spannableString.setSpan(
                ForegroundColorSpan(getColor(R.color.color_ff881d)),
                colorStartIndex,
                colorEndIndex,
                Spannable.SPAN_INCLUSIVE_INCLUSIVE
            )
            showExitDialog(this@AppProcessActivity, title, spannableString) {
                backAdJump()
            }
        }
    }


    private fun initView() {
        onBackPressedDispatcher.addCallback {
            handleBackPressed(this@AppProcessActivity)
        }

        adapter = AppProcessAdapter()
        adapter.callback = object : BaseAdapter.OnClickCallback<AppInfoBean> {
            override fun onClicked(view: View, position: Int, item: AppInfoBean) {
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${item.packageName}"))
                startActivity(intent)
            }
        }
        binding.rvAppProcess.adapter = adapter
        binding.rvAppProcess.layoutManager = LinearLayoutManager(this)
        binding.flBack.setOnClickListener { backPressed() }
        binding.tvSkip.setOnClickListener { backPressed() }
    }

    private fun initData() {
        lifecycleScope.launch(Dispatchers.IO) {
            launch { getApp() }
            launch { getMemory() }
        }
    }

    private suspend fun getApp() {
        val installedApps = packageManager.getInstalledApplications(0)
        val nonSystemApps =
            installedApps.filterNot { it.flags and ApplicationInfo.FLAG_SYSTEM != 0 }.filter { packageName != it.packageName }
        val apps = nonSystemApps.map { packageInfo ->
            val appName = packageManager.getApplicationLabel(packageInfo) as String
            val appIcon = packageInfo.loadIcon(packageManager)
            AppInfoBean(appName, appIcon, packageInfo.packageName)
        }.toMutableList()
        withContext(Dispatchers.Main) {
            binding.tvProcessSize.text = "${apps.size}"
            binding.tvTotalSize.text = "${installedApps.size}"
            adapter.submitList(apps)
        }
    }

    private suspend fun getMemory() {
        val totalMemory = AppHelps.getMemTotal(this)
        val availableMemory = AppHelps.getMemAvailable(this)
        val usedMemory = totalMemory - availableMemory

        val use: Long = usedMemory * 100 / totalMemory
        val memory = Utils.getSize(usedMemory) + "/" + Utils.getSize(totalMemory)
        withContext(Dispatchers.Main) {
            binding.tvSize.text = memory
            binding.tvProcess.text = "${use}%"
            binding.pbProcess.progress = use.toInt()
        }
    }
}