package com.zxhyis.toolss.ui.page

import android.animation.ValueAnimator
import android.content.Intent
import android.graphics.Color
import android.view.animation.LinearInterpolator
import androidx.activity.OnBackPressedCallback
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ToastUtils
import com.trustlook.sdk.cloudscan.CloudScanClient
import com.trustlook.sdk.cloudscan.CloudScanListener
import com.trustlook.sdk.data.AppInfo
import com.trustlook.sdk.data.Error
import com.trustlook.sdk.data.Region
import com.zxhyis.toolss.ad.AdmobUtils
import com.zxhyis.toolss.ad.ConfigHelper
import com.zxhyis.toolss.base.TopActivity
import com.zxhyis.toolss.databinding.ActivityLayoutVirusBinding
import com.zxhyis.toolss.logic.startActivity
import com.zxhyis.toolss.ui.AFunOb
import com.zxhyis.toolss.ui.page.result.ResultActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class VirusActivity : TopActivity<ActivityLayoutVirusBinding>() {
    override fun getViewBinding1(): ActivityLayoutVirusBinding {
        return ActivityLayoutVirusBinding.inflate(layoutInflater)
    }

    private var cloudScanClient: CloudScanClient? = null
    private var mScanList = ArrayList<AppInfo>()
    private var mProcess = 0
    override fun onStart() {
        super.onStart()
        checkPermission()
    }

    override fun init() {
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        vb.root.updatePadding(top = BarUtils.getStatusBarHeight())
        cloudScanClient = CloudScanClient.Builder(this)
            .setRegion(Region.INTL)
            .setConnectionTimeout(30000)
            .setSocketTimeout(30000)
            .build()
        vb.idVirusReturn.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                AdmobUtils.showInterstitialAd(this@VirusActivity){
                    finishToMain()
                }
            }

        })
    }
    var ifShowDialog=false
    private fun showDialog(){
        if (ConfigHelper.warmReminder) {
            startScan()
        } else {
            if(!ifShowDialog){
                ifShowDialog=true
                ConfigHelper.showWarmReminder(this) {
                        if (it) {
                            ConfigHelper.warmReminder = true
                            startScan()
                        } else {
                            finishToMain()
                        }
                }
            }

        }
    }

    override fun onPermissionsResult(isGranted: Boolean) {
        if (isGranted) {
            showDialog()
        } else {
            ToastUtils.showShort("No permission.")
            finish()
        }
    }

    private fun startScan() {
        ValueAnimator.ofFloat(0f, 360f).run {
            duration = 1000
            interpolator = LinearInterpolator()
            repeatCount = ValueAnimator.INFINITE
            repeatMode = ValueAnimator.RESTART
            addUpdateListener {
                vb.idImgAni.rotation = it.animatedValue as Float
            }
            start()
        }
        cloudScanClient?.startQuickScan(object : CloudScanListener() {
            override fun onScanStarted() {

                vb.idTvText.text = "Security scan..."
                addPro()
            }

            override fun onScanProgress(curr: Int, total: Int, result: AppInfo) {

            }

            override fun onScanError(errCode: Int, message: String) {
                var ErrorMessage = ""
                ErrorMessage = if (errCode == Error.HOST_NOT_DEFINED) {
                    "Error $errCode: HOST_NOT_DEFINED"
                } else if (errCode == Error.INVALID_INPUT) {
                    "Error  $errCode: INVALID_INPUT, no samples to scan"
                } else if (errCode == Error.SERVER_NOT_AVAILABLE) {
                    "Error $errCode: SERVER_NOT_AVAILABLE"
                } else if (errCode == Error.KEY_SERVER_NOT_AVAILABLE) {
                    "Error $errCode: KEY_SERVER_NOT_AVAILABLE"
                } else if (errCode == Error.SCAN_SERVER_NOT_AVAILABLE) {
                    "Error $errCode: SCAN_SERVER_NOT_AVAILABLE"
                } else if (errCode == Error.JSON_EXCEPTION) {
                    "Error $errCode: JSON_EXCEPTION"
                } else if (errCode == Error.IO_EXCEPTION) {
                    "Error $errCode: IO_EXCEPTION"
                } else if (errCode == Error.NO_NETWORK) {
                    "Error $errCode: NO_NETWORK"
                } else if (errCode == Error.SOCKET_TIMEOUT_EXCEPTION) {
                    "Error $errCode: SOCKET_TIMEOUT_EXCEPTION"
                } else if (errCode == Error.INVALID_KEY) {
                    "Error $errCode: INVALID_KEY, please check the key in AndroidManifest.xml"
                } else if (errCode == Error.UNSTABLE_NETWORK) {
                    "Error $errCode: UNSTABLE_NETWORT"
                } else if (errCode == Error.INVALID_SIGNATURE) {
                    "Error $errCode: INVALID_SIGNATURE"
                } else {
                    "Error $errCode $message"
                }
                //   ToastUtils.showShort("${message}")

            }

            override fun onScanCanceled() {

            }

            override fun onScanInterrupt() {}
            override fun onScanFinished(results: List<AppInfo>) {
                mScanList.addAll(results)
                //  fragment.update(results, results.size)
                //                packagenameScan();
            }
        })
    }

    private fun addPro() {
        MainScope().launch(Dispatchers.Main) {
            var index = 0
            launch {
                while (mProcess < 100) {
                    delay(100)
                    mProcess += 1
                    if (mScanList.isNotEmpty()) {
                        vb.idTvAppPackage.text = mScanList[index].packageName
                        //  index = (index + 1) % mScanList.size
                        index += 1
                        mProcess = mProcess.coerceAtLeast(index * 100 / mScanList.size)
                    }
                    vb.idTvBfb.isVisible = true
                    vb.idCurrentPro.text = "$mProcess"
                    vb.idProcess.progress = mProcess
                }

                val mVirsList = mScanList.filter {
                    it.score > 5
                }

                AdmobUtils.showInterstitialAd(this@VirusActivity) {
                    if (mVirsList.isNotEmpty()) {
                         ConfigHelper.riskAppList = mVirsList
                        startActivity(Intent(this@VirusActivity, VirusAppActivity::class.java))
                        finish()
                    } else {
                        startActivity<ResultActivity>("from" to AFunOb.Antivirus)
                        finish()
                    }
                }


            }

        }

    }

    override fun onDestroy() {
        super.onDestroy()
        cloudScanClient?.cancelScan()
    }
}