package com.base.appzxhy.ui.malware

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.base.appzxhy.R
import com.base.appzxhy.base.BaseActivity
import com.base.appzxhy.bean.AppInfoBean
import com.base.appzxhy.business.ads.AdsMgr
import com.base.appzxhy.business.ads.AdsShowCallBack
import com.base.appzxhy.databinding.ActivityMalwareCleanBinding
import com.base.appzxhy.databinding.ItemMalwareCleanBinding
import com.base.appzxhy.utils.FileUtils
import com.trustlook.sdk.cloudscan.CloudScanListener
import com.trustlook.sdk.data.AppInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.random.Random
import androidx.core.net.toUri
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.base.appzxhy.BuildConfig
import com.base.appzxhy.base.LottieEnum
import com.base.appzxhy.bean.FeatureBean.Companion.ANTIVIRUS
import com.base.appzxhy.bean.FeatureBean.Companion.JUNK_CLEAN
import com.base.appzxhy.bean.FeatureBean.Companion.setFunctionTodayUsed
import com.base.appzxhy.ui.cleanresult.CleanResultActivity
import com.base.appzxhy.utils.LogEx


class MalwareCleanActivity : BaseActivity<ActivityMalwareCleanBinding>(ActivityMalwareCleanBinding::inflate) {

    private var appList = mutableListOf<AppInfoBean>()
    private val adapter by lazy(LazyThreadSafetyMode.NONE) {
        class ViewHolder(val binding: ItemMalwareCleanBinding) :
            RecyclerView.ViewHolder(binding.root)

        object : RecyclerView.Adapter<ViewHolder>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
                val binding = ItemMalwareCleanBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
                return ViewHolder(binding)
            }

            override fun getItemCount(): Int = appList.size

            override fun onBindViewHolder(holder: ViewHolder, position: Int) {
                val item = appList[position]
                holder.binding.ivIcon.setImageDrawable(item.icon)
                holder.binding.tvName.text = item.appName
                holder.binding.tvLevel.text = getLevel(item.score ?: 0)
                holder.binding.viewLine.visibility =
                    if (position == itemCount - 1) View.GONE else View.VISIBLE
                holder.itemView.setOnClickListener {
                    item.isSelected = !item.isSelected
                    AdsMgr.showInsert(this@MalwareCleanActivity, showCallBack = object : AdsShowCallBack() {
                        override fun next() {
                            uninstall(0, listOf(item))
                        }
                    })
                }
            }
        }

    }

    private fun getLevel(score: Int): String {
        return if (score <= 5) {
            "safe"
        } else if (score in 6..7) {
            "Risk"
        } else {
            "malware"
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun uninstall(position: Int, list: List<AppInfoBean>) {
        val packageName = list[position].packageName
        val intent = Intent(Intent.ACTION_DELETE, "package:$packageName".toUri())
        launcher.launch(intent) {
            if (isUninstall(packageName)) {
                appList.removeIf {
                    it.packageName == packageName
                }
                runOnUiThread {
                    adapter.notifyDataSetChanged()
                    updateUninstall()
                }
            }
            if (position < list.size - 1) uninstall(position + 1, list)
            else {
                updateView(false)
            }
        }
    }

    private fun isUninstall(packageName: String): Boolean {
        val intent = packageManager.getLaunchIntentForPackage(packageName)
        return intent == null
    }

    @SuppressLint("SetTextI18n")
    private fun updateUninstall() {
        val list = appList.filter { it.isSelected }
        val size = if (list.isEmpty()) "" else " ${list.size} ${getString(R.string.apps)}"
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun malwareClean(list: List<AppInfoBean>) {
        lifecycleScope.launch(Dispatchers.Default) {
            val installApps = mutableListOf<AppInfoBean>()
            list.forEach {
                if (it.isInstall == true) installApps.add(it)
                else {
                    it.apkPath?.also {
                        launch(Dispatchers.IO) {
                            FileUtils.deleteFile(it)
                        }
                    }
                    appList.remove(it)
                }
            }

            if (installApps.isNotEmpty()) {
                uninstall(0, installApps)
            } else {
                withContext(Dispatchers.Main) {
                    adapter.notifyDataSetChanged()
                    updateUninstall()
                }
            }
        }
    }

    private var isScanning = false
    private fun initData(isScan: Boolean = isScanning) {
        if (isScan) return
        isScanning = true
        CloudScan.scanClient.startQuickScan(object : CloudScanListener() {
            override fun onScanStarted() {
                LogEx.logDebug(TAG, "onScanStarted")
            }

            override fun onScanCanceled() {
                LogEx.logDebug(TAG, "onScanCanceled")
                scanFinish()
            }

            override fun onScanProgress(p0: Int, p1: Int, p2: AppInfo?) {
                LogEx.logDebug(TAG, "onScanProgress")
            }

            @SuppressLint("NotifyDataSetChanged")
            override fun onScanFinished(dataList: MutableList<AppInfo>?) {

                //Log.e("CloudScan", "onScanFinished")
                scanFinishData(dataList)
            }

            override fun onScanError(p0: Int, p1: String?) {
                LogEx.logDebug(TAG, "onScanError")
                isScanning = false
                scanError()
            }

            override fun onScanInterrupt() {
                isScanning = false
                scanError()
            }
        })
    }

    fun scanError() {
        if (BuildConfig.DEBUG) return
        val dialog = ErrorScanDialog(this@MalwareCleanActivity)
        dialog.action = {
            finish()
        }
        dialog.showDialog()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun scanFinishData(dataList: MutableList<AppInfo>?) {


        lifecycleScope.launch(Dispatchers.Default) {
            val realList = mutableListOf<AppInfoBean>()
            dataList?.forEach {
                if (!it.isSystemApp && (it.score > 5 || BuildConfig.DEBUG)) {
                    var isInstall: Boolean
                    // Log.e("CloudScan", "${it.source}  ${it.apkPath}  ${it.toJSON(this@MalwareCleanActivity)}")
                    val icon = try {
                        val res = packageManager.getApplicationIcon(it.packageName)
                        isInstall = true
                        res
                    } catch (e: PackageManager.NameNotFoundException) {
                        isInstall = false
                        val info = packageManager.getPackageArchiveInfo(
                            it.apkPath,
                            PackageManager.GET_ACTIVITIES
                        )
                        if (info != null) {
                            info.applicationInfo?.let { packageManager.getApplicationIcon(it) }
                        } else {
                            AppCompatResources.getDrawable(this@MalwareCleanActivity, R.drawable.icon_apk)
                        }
                    }
                    realList.add(
                        AppInfoBean(
                            it.appName,
                            icon!!,
                            it.packageName,
                            false,
                            isInstall,
                            it.score,
                            it.apkPath
                        )
                    )
//                            withContext(Dispatchers.Main) {
//                                adapter.notifyItemInserted(appList.size)
//                            }
                }
            }

            if (BuildConfig.DEBUG) {
                realList.add(
                    AppInfoBean(
                        "AntiVirus Phone Manager",
                        AppCompatResources.getDrawable(this@MalwareCleanActivity, R.drawable.icon_apk)!!,
                        "com.tool.fast.phone",
                        false,
                        true,
                        5,
                        "apkPath/apkPath/apkPath"
                    )
                )
            }

            withContext(Dispatchers.Main) {
                val durationTime = Random.nextLong(3000, 3500)
                delay(durationTime)
                appList.clear()
                appList.addAll(realList)
                scanFinish()
                adapter.notifyDataSetChanged()
                updateView(true)

            }
        }
    }

    private fun scanFinish() {
        isScanning = false
        stopAnimation()
    }

    fun stopAnimation() {
        binding.layoutAnimation.lottieAnimation.clearAnimation()
        binding.layoutAnimation.root.visibility = View.GONE
        isBackDisable = false
    }

    @SuppressLint("SetTextI18n")
    private fun updateView(jump: Boolean) {
        binding.ivLogo.visibility = if (appList.isEmpty()) View.GONE else View.VISIBLE
        binding.tvCount.visibility = if (appList.isEmpty()) View.GONE else {
            binding.tvCount.text = getString(R.string.issue, appList.size.toString())
            View.VISIBLE
        }
        binding.tvUnit.visibility = if (appList.isEmpty()) View.GONE else View.VISIBLE
        binding.rvMalware.visibility = if (appList.isEmpty()) View.GONE else View.VISIBLE
        binding.ivEmpty.visibility = if (appList.isEmpty()) View.VISIBLE else View.GONE

        if (appList.isEmpty()) {
            if (jump) {
                CleanResultActivity.functionKey = ANTIVIRUS
                CleanResultActivity.titleName = getString(R.string.malware_scan)
                goToAc(CleanResultActivity::class.java)
            }
        } else {
            AdsMgr.showNative(binding.flAd, R.layout.layout_admob_native_custom)
        }
    }

    override fun useDefaultImmersive() {
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom)
            binding.clTop.setPadding(0, systemBars.top, 0, 0)
            insets
        }
    }

    override fun initView() {
        super.initView()
        showAdAnimation(LottieEnum.MALWARE_SCAN)
        binding.rvMalware.adapter = adapter
        binding.rvMalware.layoutManager = LinearLayoutManager(this)

        initData()

        if (BuildConfig.DEBUG) {
            scanFinishData(null)
        }

        setFunctionTodayUsed(ANTIVIRUS)

    }

    override fun initListener() {
        super.initListener()
        binding.flBack.setOnClickListener { onBackPressedDispatcher.onBackPressed() }
    }

    override fun handleBackCallBack() {
        super.handleBackCallBack()
    }
}