package com.test.mydemo3.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.ListView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.cleanmaster.junk.bean.SDcardRubbishResult
import com.cloud.cleanjunksdk.ad.AdvBean
import com.cloud.cleanjunksdk.cache.CacheBean
import com.cloud.cleanjunksdk.filescan.ApkBean
import com.cloud.cleanjunksdk.filescan.LogBean
import com.cloud.cleanjunksdk.filescan.TmpBean
import com.cloud.cleanjunksdk.residual.ResidualBean
import com.cloud.cleanjunksdk.task.JunkScanCallback
import com.cm.plugincluster.junkengine.junk.bean.MediaFile
import com.cm.plugincluster.junkengine.junk.engine.MEDIA_TYPE
import com.test.mydemo3.MyApplication
import com.test.mydemo3.R
import com.test.mydemo3.adapter.CleanAdapter
import com.test.mydemo3.antivirus.AntivirusActivity
import com.test.mydemo3.model.CleanBean
import com.test.mydemo3.model.FileBean
import com.test.mydemo3.util.FileUtil
import java.io.File

class CleanActivity : AppCompatActivity() {
    private var mQuitBtn: ImageView? = null
    private var mHintTv: TextView? = null
    private var mProgress: ProgressBar? = null
    private lateinit var mListView: ListView
    private var mCleanAdapter: CleanAdapter? = null
    private var mAdView: View? = null
    private lateinit var mAnimation: View
    private lateinit var mCleanBtn: TextView
    private var junkScanCallback : JunkScanCallback? = null
    private var mCount = 0
//    private var mBooleans = ArrayList<Boolean>()

    private var mIsApkScanSuccess = false
    private var mIsCacheScanSuccess = false
    private var mIsTmpScanSuccess = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_clean)
        initJunkScanCallBack()
        initView()
        if (MyApplication.mCleanSdk != null){
            MyApplication.mCleanSdk?.cancel()
//            MyApplication.mCleanSdk?.startScan(junkScanCallback, true)
        }
    }

    private val mCleanBeans = ArrayList<CleanBean>()

    private fun initView() {
        mQuitBtn = findViewById(R.id.clean_quit_btn)
        mHintTv = findViewById(R.id.clean_hint_text)
        mProgress = findViewById(R.id.clean_progress)
        mListView = findViewById(R.id.clean_list_view)
        mAdView = findViewById(R.id.ad_layout)
        mAnimation = findViewById(R.id.clean_animation)
        mCleanBtn = findViewById(R.id.clean_click_text)
        CleanAdapter.isCleanOver = false
        setViewOnclickListener()

        var cleanBean =  CleanBean()
        cleanBean.typeName = "Uninstall remains"
        mCleanBeans.add(cleanBean)

        cleanBean = CleanBean()
        cleanBean.typeName = "aps(s)"
        mCleanBeans.add(cleanBean)

        cleanBean = CleanBean()
        cleanBean.typeName = "Memory cleanup"
        mCleanBeans.add(cleanBean)

        cleanBean = CleanBean()
        cleanBean.typeName = "Cache junk"
        mCleanBeans.add(cleanBean)

        cleanBean = CleanBean()
        cleanBean.typeName = "Other trash"
        mCleanBeans.add(cleanBean)
        mCleanAdapter = CleanAdapter(mCleanBeans, this)
        mListView.adapter = mCleanAdapter

        MyApplication.mCleanSdk?.startScan(junkScanCallback, false)
        MyApplication.mCleanSdk?.timeout(60000)

        val handler = Handler(Looper.getMainLooper())

        val runnable = object : Runnable{
            override fun run() {
                if (mCount < 99){
                    mCount ++
                    mProgress?.setProgress(mCount)
                    handler.postDelayed(this, 300)
                }
            }
        }
        handler.postDelayed(runnable, 0)

    }


    private fun setViewOnclickListener() {
        mQuitBtn?.setOnClickListener {
            finish()
        }
        findViewById<View>(R.id.go_to_antivirus).setOnClickListener {
            startActivity(Intent(this, AntivirusActivity::class.java))
        }
        findViewById<View>(R.id.go_to_battery).setOnClickListener {
            startActivity(Intent(this, BatteryActivity::class.java))
        }
        findViewById<View>(R.id.go_to_scan_large).setOnClickListener {
            startActivity(Intent(this, ScanLargeFilesActivity::class.java))
        }
        findViewById<View>(R.id.go_to_scan_similar_images).setOnClickListener {
            startActivity(Intent(this, SimilarImagesActivity::class.java))
        }
        findViewById<View>(R.id.clean_click_text).setOnClickListener {
            mAnimation.visibility = View.VISIBLE
            Thread(Runnable {
                Thread.sleep(1000)
                for (fileBeans in mCleanAdapter?.mFileCheckedItemList!!){
                    for (fileBean in fileBeans){
                        try {
                            MyApplication.mCleanSdk?.delete(File(fileBean.filePath))
                        }catch (e: Exception){
                            e.printStackTrace()
                        }
                    }
                }
                runOnUiThread {
                    mListView.visibility = View.GONE
                    mAnimation.visibility = View.GONE
                    findViewById<View>(R.id.clean_over_layout).visibility = View.VISIBLE
                }
            }).start()
        }
    }

    fun initJunkScanCallBack(){
        val TAG = "yanglin"
        junkScanCallback = object :JunkScanCallback{
            override fun onStart() {

//                Log.e(TAG, "onStart: ", )
            }

            override fun error(p0: Int, p1: Throwable?) {
                Log.e(TAG, "error: $p0", )
            }

            override fun onAdJunkEmitOne(p0: AdvBean?) {
//                Log.e(TAG, "onAdJunkEmitOne: $p0", )
                mHintTv?.text = "Scanning: ${p0?.path}.."
            }

            override fun onAdJunkSucceed() {
//                Log.e(TAG, "onAdJunkSucceed: ", )
//                mCount +=10
//                mProgress?.setProgress(mCount)
            }

            override fun onApkJunkEmitOne(p0: ApkBean?) {
//                Log.e(TAG, "onApkJunkEmitOne: $p0", )
                val fileBean = FileBean()
                fileBean.fileName = p0?.appName!!
                fileBean.drawable = p0.appIcon
                fileBean.filePath = p0.path
                fileBean.fileSize = p0.size
                fileBean.fileType = FileUtil.getFileType(File(p0.path))
                mCleanBeans[1].fileBeans.add(fileBean)
                mHintTv?.text = "Scanning: ${p0.appName}.."


            }

            override fun onApkJunkScanSucceed() {
                Log.e(TAG, "onApkJunkScanSucceed: ", )
//                mCount +=10
//                mProgress?.setProgress(mCount)
                mIsApkScanSuccess = true

                setAdapter()

            }

            override fun onTmpJunkEmitOne(p0: TmpBean?) {
//                Log.e(TAG, "onTmpJunkEmitOne: $p0", )
                val fileBean = FileBean()
                fileBean.fileName = p0?.name!!
                fileBean.filePath = p0.path
                fileBean.fileSize = p0.size
                fileBean.fileType = FileUtil.getFileType(File(p0.path))
                mCleanBeans[4].fileBeans.add(fileBean)
                mHintTv?.text = "Scanning: ${p0.path}.."
            }

            override fun onTmpJunkScanSucceed() {
//                Log.e(TAG, "onTmpJunkScanSucceed: ", )
//                mCount +=10
//                mProgress?.setProgress(mCount)
                mIsTmpScanSuccess = true
                setAdapter()

            }

            override fun onLogJunkEmitOne(p0: LogBean?) {
                Log.e(TAG, "onLogJunkEmitOne: $p0", )
//                val fileBean = FileBean()
//                fileBean.fileName = p0?.name!!
//                fileBean.filePath = p0.path
//                fileBean.fileSize = p0.size
//                fileBean.fileType = FileUtil.getFileType(File(p0.path))
//                mCleanBeans[4].fileBeans.add(fileBean)
                mHintTv?.text = "Scanning: ${p0?.path}.."


            }

            override fun onLogJunkScanSucceed() {
//                Log.e(TAG, "onLogJunkScanSucceed: ", )
//                mCount += 10
//                mProgress?.setProgress(mCount)
                setAdapter()
            }

            override fun onCacheJunkEmitOne(p0: CacheBean?) {
//                Log.e(TAG, "onCacheJunkEmitOne: $p0", )
                val fileBean = FileBean()
                for (pathBean in p0?.pathBeen!!){
                    fileBean.fileName = p0.packageName
                    fileBean.filePath = pathBean.cleanPath
                    fileBean.hint = p0.appName
                    fileBean.fileSize = pathBean.size
                    mCleanBeans[3].fileBeans.add(fileBean)
                    mHintTv?.text = "Scanning: ${p0.packageName}.."
                }
            }

            override fun onCacheJunkSucceed() {
//                Log.e(TAG, "onCacheJunkSucceed: ", )
//                mCount +=10
//                mProgress?.setProgress(mCount)
                mIsCacheScanSuccess = true
                setAdapter()
            }

            @SuppressLint("SetTextI18n")
            override fun onResidualEmitOne(p0: ResidualBean?) {
//                Log.e(TAG, "onResidualEmitOne: $p0", )
                val path = p0!!.path
                mHintTv?.text = "Scanning: ${path!!}.."

            }

            override fun onResidualJunkSucceed() {
//                Log.e(TAG, "onResidualJunkSucceed: ", )
//                mCount +=10
//                mProgress?.setProgress(mCount)

                setAdapter()
            }

            override fun onThumbnailJunkEmitOne(p0: SDcardRubbishResult?) {
//                Log.e(TAG, "onThumbnailJunkEmitOne: $p0", )
//                val fileBean = FileBean()
//                fileBean.fileName = p0?.name!!
//                fileBean.fileSize = p0.size
//                mCleanBeans[4].fileBeans.add(fileBean)
                mHintTv?.text = "Scanning: ${p0!!.name}.."
            }

            override fun onThumbnailJunkScanSucceed() {
//                Log.e(TAG, "onThumbnailJunkScanSucceed: ", )
                setAdapter()

            }

            override fun onMediaFileJunkEmitOne(p0: MEDIA_TYPE?, p1: MediaFile?) {
//                Log.e(TAG, "onMediaFileJunkEmitOne: $p0, $p1", )
                mHintTv?.text = "Scanning: ${p1!!.mApkName}.."
            }

            override fun onMediaFileJunkScanSucceed(p0: MEDIA_TYPE?) {
//                Log.e(TAG, "onMediaFileJunkScanSucceed: $p0", )
//                mCount +=10
//                mProgress?.setProgress(mCount)
            }

            override fun onTimeOut() {
//                Log.e(TAG, "onTimeOut: ", )
            }

        }
    }

    private fun setAdapter() {
        if (mIsApkScanSuccess && mIsCacheScanSuccess && mIsTmpScanSuccess) {
//            MyApplication.mCleanSdk?.
            findViewById<View>(R.id.battery_animation_btn).visibility = View.GONE
            mCleanAdapter?.setData(mCleanBeans)
            CleanAdapter.isCleanOver = true
            var allSize: Long = 0
            for (size in mCleanAdapter?.mAllSizes!!) {
                allSize += size
            }
            mCount = 0
            mProgress?.setProgress(100)
            mProgress?.visibility = View.GONE
            mHintTv?.visibility = View.GONE
            mCleanBtn.visibility = View.VISIBLE
            mCleanBtn.text = if (allSize > 1024 * 1024 * 1024) {
                "One-click cleanup of ${allSize / 1024 / 1024 / 1024} GB"
            } else if (allSize > 1024 * 1024) {
                "One-click cleanup of ${allSize / 1024 / 1024} MB"
            } else if (allSize > 1024) {
                "One-click cleanup of ${allSize / 1024} KB"
            } else {
                "One-click cleanup of ${allSize} B"
            }

        }
    }

}