package com.xm.test.myfilemaster.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.ProgressBar
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
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.xm.test.myfilemaster.MyApplication
import com.xm.test.myfilemaster.R
import com.xm.test.myfilemaster.adapter.CleanAdapter
import com.xm.test.myfilemaster.adapter.CleanAdapter2
import com.xm.test.myfilemaster.antivirus.AntivirusActivity
import com.xm.test.myfilemaster.model.CleanBean
import com.xm.test.myfilemaster.model.FileBean
import com.xm.test.myfilemaster.util.FileUtil
import java.io.File

class CleanActivity : AppCompatActivity(), CleanAdapter2.IClean {
    private var mQuitBtn: ImageView? = null
    private var mHintTv: TextView? = null
    private var mProgress: ProgressBar? = null
    private lateinit var mListView: RecyclerView
    private lateinit var mCleanSuccessView: View
    private lateinit var mScaningView: View
    private lateinit var mCleanSizeSuccessTv: TextView

    //    private var mCleanAdapter: CleanAdapter? = null
    private var mCleanAdapter2: CleanAdapter2? = 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)
        mCleanSuccessView = findViewById(R.id.clean_success_layout)
        mScaningView = findViewById(R.id.battery_animation_btn)
        mCleanSizeSuccessTv = findViewById(R.id.clean_success_size_text)
        CleanAdapter.isCleanOver = false
        mCleanBtn.text = "One-click cleanup of 0 B"
        mCleanSizeSuccessTv.text = "Successfully cleaned up 1KB of junk!"

        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)
        mCleanAdapter2 = CleanAdapter2(this)
        mListView.adapter = mCleanAdapter2

        mCleanAdapter2?.setData(mCleanBeans)

        MyApplication.mCleanSdk?.startScan(junkScanCallback, true)
        MyApplication.mCleanSdk?.timeout(30000)

        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)
                mCleanAdapter2?.mFileCheckedItemList?.forEach {
                    MyApplication.mCleanSdk?.delete(File(it.filePath))
                }
                runOnUiThread {
                    mListView.visibility = View.GONE
                    mAnimation.visibility = View.GONE
                    findViewById<View>(R.id.ad_layout).visibility = View.GONE
                    findViewById<View>(R.id.over_layout).visibility = View.VISIBLE
                    mCleanSuccessView.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: ", )
                    setAdapter()
                }

            }
        }

        private fun setAdapter() {
//            if (mIsApkScanSuccess && mIsCacheScanSuccess && mIsTmpScanSuccess) {
//            MyApplication.mCleanSdk?.
//                findViewById<View>(R.id.battery_animation_btn).visibility = View.GONE
                mCleanAdapter2?.setData(mCleanBeans)
                CleanAdapter.isCleanOver = true
                mCount = 0
                mProgress?.setProgress(100)
                mProgress?.visibility = View.GONE
                mHintTv?.visibility = View.GONE
            mScaningView.visibility = View.GONE
                mCleanBtn.visibility = View.VISIBLE



//            }
        }

    override fun OnChekedItemListener(size: Long) {

        val sizeStr = if (size > 1024 * 1024 * 1024) {
            "${size / 1024 / 1024 / 1024}GB"
        } else if (size > 1024 * 1024) {
            "${size / 1024 / 1024}MB"
        } else if (size > 1024) {
            "${size / 1024}KB"
        } else {
            "${size}B"
        }
        mCleanBtn.text = "One-click cleanup of $sizeStr"
        mCleanSizeSuccessTv.text = "Successfully cleaned up $sizeStr of junk!"
    }


}