package pxds.etmo

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Environment
import android.text.format.Formatter
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.activity.addCallback
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.PermissionUtils
import com.test.basd.supercleanermax.R
import com.test.basd.supercleanermax.databinding.FwfndxBinding
import com.test.basd.supercleanermax.databinding.NdgxopBinding
import com.test.basd.supercleanermax.databinding.SbpibkBinding
import pxds.dlpf.buoz.fico.Faim.showFileDetailDialog
import pxds.dlpf.buoz.fico.Ipnk.inflate
import pxds.dlpf.buoz.fico.Ouwp.showFileDeleteDialog
import pxds.etmo.Ozev.Filter.Companion.KEY_1_MONTH
import pxds.etmo.Ozev.Filter.Companion.KEY_1_WEEK
import pxds.etmo.Ozev.Filter.Companion.KEY_1_YEAR
import pxds.etmo.Ozev.Filter.Companion.KEY_3_MONTHS
import pxds.etmo.Ozev.Filter.Companion.KEY_6_MONTHS
import pxds.etmo.Ozev.Filter.Companion.KEY_ALL_TIME
import pxds.etmo.Ozev.Filter.Companion.KEY_ALL_TYPES
import pxds.etmo.Ozev.Filter.Companion.KEY_APK
import pxds.etmo.Ozev.Filter.Companion.KEY_ARCHIVES
import pxds.etmo.Ozev.Filter.Companion.KEY_AUDIO
import pxds.etmo.Ozev.Filter.Companion.KEY_DOCUMENT
import pxds.etmo.Ozev.Filter.Companion.KEY_IMAGE
import pxds.etmo.Ozev.Filter.Companion.KEY_OTHER_TYPES
import pxds.etmo.Ozev.Filter.Companion.KEY_SIZE_100_MB
import pxds.etmo.Ozev.Filter.Companion.KEY_SIZE_10_MB
import pxds.etmo.Ozev.Filter.Companion.KEY_SIZE_1_GB
import pxds.etmo.Ozev.Filter.Companion.KEY_SIZE_500_MB
import pxds.etmo.Ozev.Filter.Companion.KEY_SIZE_50_MB
import pxds.etmo.Ozev.Filter.Companion.KEY_VIDEO
import pxds.hpls.xkxo.Eqvl
import pxds.lmmd.zmwf.Bpfw
import pxds.lmmd.zmwf.Egac
import pxds.lmmd.zmwf.Khko.setTrackedOnClickListener
import pxds.lmmd.zmwf.Khko.string
import pxds.lmmd.zmwf.Oejm
import pxds.lmmd.zmwf.Onaw
import pxds.lmmd.zmwf.jyyf.hwbn.wzxb.Utdc
import pxds.vazp.FileBean
import java.io.File

/**
 * 大文件清理
 */
class Ozev : Bpfw<FwfndxBinding>() {
    override val isLightMode = true
    private val TAG = R.string.ޜލޥރޡ_D.string()
    private val listTypes = listOf(
        Filter(KEY_ALL_TYPES, true), Filter(KEY_IMAGE), Filter(KEY_VIDEO), Filter(KEY_AUDIO), Filter(KEY_DOCUMENT), Filter(KEY_ARCHIVES), Filter(KEY_APK), Filter(KEY_OTHER_TYPES), )

    private val listSizes = listOf(
        Filter(KEY_SIZE_10_MB, true), Filter(KEY_SIZE_50_MB), Filter(KEY_SIZE_100_MB), Filter(KEY_SIZE_500_MB), Filter(KEY_SIZE_1_GB), )

    private val listTimes = listOf(
        Filter(KEY_ALL_TIME, true), Filter(KEY_1_WEEK), Filter(KEY_1_MONTH), Filter(KEY_3_MONTHS), Filter(KEY_6_MONTHS), Filter(KEY_1_YEAR), )

    private val largeFileList = arrayListOf<FileBean>()
    private lateinit var adapter: Eqvl

    private var fileType = KEY_ALL_TYPES
    private var filterSize = KEY_SIZE_10_MB
    private var filterTime = KEY_ALL_TIME

    override val binding: FwfndxBinding by lazy {
        FwfndxBinding.inflate(layoutInflater)
    }

    override fun initView() {
        binding.kmkhdqf.isEnabled = false
        binding.udpyhoi.isEnabled = false
        binding.jtqlbpu.isEnabled = false

        adapter = Eqvl(
            itemClick = { fileBean ->
                this.showFileDetailDialog(fileBean)
            }, selectClick = { files ->
                if (files.isNotEmpty()) {
                    binding.afhzdgi.background = ContextCompat.getDrawable(this, R.drawable.byhgnoow)
                    binding.afhzdgi.isEnabled = true
                    val size = files.sumOf { it.size }
                    val sizeF = Formatter.formatFileSize(this, size)
                    binding.afhzdgi.text = R.string.ފޡޕހޞ_D.string((sizeF).toString())
                } else {
                    binding.afhzdgi.background = ContextCompat.getDrawable(this, R.drawable.ixyeptmj)
                    binding.afhzdgi.isEnabled = false
                    binding.afhzdgi.text = R.string.ހދޜދޕ_D.string()
                }
            }
        )
        binding.hynncaa.adapter = adapter

        binding.afhzdgi.setTrackedOnClickListener {
            this.showFileDeleteDialog {
                val deleteList = arrayListOf<FileBean>()
                adapter.getSelectData().forEach {
                    val file = File(it.path)
                    try {
                        if (file.delete()) {
                            deleteList.add(it)
                        }
                    } catch (e: Exception) {
                    }
                }
                largeFileList.removeAll(deleteList.toSet())
                adapter.removeData(deleteList)
                binding.afhzdgi.background = ContextCompat.getDrawable(this, R.drawable.ixyeptmj)
                binding.afhzdgi.isEnabled = false
                binding.afhzdgi.text = R.string.ހދޜދޕ_D.string()
            }
        }

        binding.kmkhdqf.setTrackedOnClickListener {
            showPopupWindow(binding.xoqllob, 0, listTypes)
        }
        binding.udpyhoi.setTrackedOnClickListener {
            showPopupWindow(binding.xoqllob, 1, listSizes)
        }
        binding.jtqlbpu.setTrackedOnClickListener {
            showPopupWindow(binding.xoqllob, 2, listTimes)
        }
        binding.ngdqagq.setTrackedOnClickListener {
            Utdc.showInterstitialAd(this) {
                finishToMain()
            }
        }
        onBackPressedDispatcher.addCallback {
            Utdc.showInterstitialAd(this@Ozev) {
                finishToMain()
            }
        }

        binding.egetnag.text = fileType
        binding.wkrduju.text = filterSize
        binding.smokwld.text = filterTime

        val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Environment.isExternalStorageManager()
        } else {
            PermissionUtils.isGranted(PermissionConstants.STORAGE)
        }
        if (flag) {
            isplay += 1
            playLottie()
        }
        checkPermission()
    }

    var isplay = 0
    override fun onPermissionsResult(isGranted: Boolean) {
        super.onPermissionsResult(isGranted)
        if (isGranted) {
            isplay += 1
            if (isplay == 1) {
                playLottie()
            }
            initList()
        } else {
            finishToMain()
        }
    }

    private fun initList() {
        Oejm.getFileList(onUpdate = {
            Oejm.fileList.toList().filter {
                it.isLargeFile() && it !in largeFileList
            }.onEach {
                it.isSelect = false
            }.let {
                if (it.isNotEmpty()) {
                    Egac.logDebug(TAG, R.string.ޥޣޠބބ_D.string((it).toString()))

                    if (!binding.kmkhdqf.isEnabled) {
                        binding.kmkhdqf.isEnabled = true
                        binding.udpyhoi.isEnabled = true
                        binding.jtqlbpu.isEnabled = true
                    }

                    largeFileList.addAll(it)
                    binding.dboqifh.visibility = View.GONE

                    adapter.setData(largeFileList)
                }
            }
        }, onEnd = {
            Egac.logDebug(TAG, R.string.ޑޣޜގއ_D.string())
            binding.dboqifh.visibility = View.GONE
            adapter.setData(largeFileList)
            if (largeFileList.isEmpty()) {
                binding.wzdbrcf.visibility = View.VISIBLE
            }
        })
    }

    data class Filter(
        val keyName: String = "", var isSelect: Boolean = false, ) {
        companion object {
            val KEY_ALL_TYPES = R.string.ޚޤތސޖ_D.string()
            val KEY_IMAGE = R.string.ޛޠޢޜވ_D.string()
            val KEY_VIDEO = R.string.ޏޓޅދބ_D.string()
            val KEY_AUDIO = R.string.އބޙމސ_D.string()
            val KEY_DOCUMENT = R.string.ކޕބދފ_D.string()
            val KEY_ARCHIVES = R.string.ޜހރޕމ_D.string()
            val KEY_APK = R.string.ސހޘޙދ_D.string()
            val KEY_OTHER_TYPES = R.string.ޓޜޙޒމ_D.string()

            val KEY_SIZE_10_MB = R.string.ޡޅޝރޏ_D.string()
            val KEY_SIZE_50_MB = R.string.ޅއޟތޕ_D.string()
            val KEY_SIZE_100_MB = R.string.ސސރކޜ_D.string()
            val KEY_SIZE_500_MB = R.string.ސރހޝޣ_D.string()
            val KEY_SIZE_1_GB = R.string.ބބޖޛޔ_D.string()

            val KEY_ALL_TIME = R.string.ޕނޘޏޘ_D.string()
            val KEY_1_WEEK = R.string.ޏގސޖއ_D.string()
            val KEY_1_MONTH = R.string.ޠސޜޑޥ_D.string()
            val KEY_3_MONTHS = R.string.ބފބޣޔ_D.string()
            val KEY_6_MONTHS = R.string.ޘލއދލ_D.string()
            val KEY_1_YEAR = R.string.ސޙޥޒވ_D.string()
        }
    }

    private fun playLottie(showFinish: (() -> Unit)? = null) {
        binding.ekqopho.isVisible = true

        Egac.logDebug(TAG, R.string.ޑޓވބބ_D.string())
        binding.root.postDelayed({
            Utdc.showInterstitialAd(this) {
                binding.ekqopho.isVisible = false
                showFinish?.invoke()
                Egac.logDebug(TAG, R.string.ޝޝޢނއ_D.string())
            }
        }, 6000)
    }

    private fun showPopupWindow(view: View, type: Int = 0, list: List<Filter>) {
        val popupWindowView = layoutInflater.inflate(R.layout.ndgxop, null)
        val location = IntArray(2)
        binding.xoqllob.getLocationOnScreen(location)
        val anchorBottom: Int = location[1] + binding.xoqllob.height
        val screenHeight: Int = getResources().displayMetrics.heightPixels
        val height = screenHeight - anchorBottom + this.resources.getDimensionPixelSize(R.dimen.ބޚޥޛޖ)

        val popupWindow = PopupWindow(popupWindowView, view.width, height, true)
        popupWindow.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        popupWindow.isOutsideTouchable = true
        popupWindow.isTouchable = true
        val pBinding = NdgxopBinding.bind(popupWindowView)

        if (type == 0) {
            pBinding.xijyvon.visibility = View.GONE
        }
        if (type == 1) {
            pBinding.xijyvon.text = R.string.އޅޟޟލ_D.string()
        }
        if (type == 2) {
            pBinding.xijyvon.text = R.string.ޙލޡޕޙ_D.string()
        }
        class KKK(view: View) : RecyclerView.ViewHolder(view)

        val filterAdapter = object : RecyclerView.Adapter<KKK>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): KKK {
                return KKK(R.layout.sbpibk.inflate(parent))
            }

            override fun getItemCount(): Int {
                return list.size
            }

            override fun onBindViewHolder(holder: KKK, position: Int) {
                val binding = SbpibkBinding.bind(holder.itemView)
                val context = holder.itemView.context
                val data = list[position]
                binding.lcfqyhf.text = data.keyName
                if (data.isSelect) {
                    binding.lcfqyhf.setTextColor(ContextCompat.getColor(context, R.color.ޛޚޝޣޠ))
                    binding.khqvveq.visibility = View.VISIBLE
                } else {
                    binding.lcfqyhf.setTextColor(ContextCompat.getColor(context, R.color.ށޏޅޗކ))
                    binding.khqvveq.visibility = View.INVISIBLE
                }
                binding.root.setTrackedOnClickListener {
                    val old = list.find { it.isSelect }
                    if (data == old) {
                        return@setTrackedOnClickListener
                    } else {
                        data.isSelect = true
                        old?.isSelect = false
                        filterTypeList(type, data.keyName)
                        popupWindow.dismiss()
                    }
                }
            }

        }
        pBinding.hynncaa.adapter = filterAdapter
        pBinding.root.setTrackedOnClickListener {
            popupWindow.dismiss()
        }

        popupWindow.showAsDropDown(view)
    }

    private fun filterTypeList(filterType: Int, keyName: String) {
        Egac.logDebug(TAG, R.string.ޝވޡތޕ_D.string((filterType).toString(), (keyName).toString()))
        if (filterType == 0) {
            binding.egetnag.text = keyName
            fileType = keyName
        }
        if (filterType == 1) {
            binding.wkrduju.text = keyName
            filterSize = keyName
        }
        if (filterType == 2) {
            binding.smokwld.text = keyName
            filterTime = keyName
        }

        val tempList1 = when (fileType) {
            KEY_ALL_TYPES -> largeFileList
            KEY_IMAGE -> largeFileList.filter { it.isImage() }
            KEY_VIDEO -> largeFileList.filter { it.isVideo() }
            KEY_AUDIO -> largeFileList.filter { it.isAudio() }
            KEY_DOCUMENT -> largeFileList.filter { it.isDoc() }
            KEY_ARCHIVES -> largeFileList.filter { it.isZip() }
            KEY_APK -> largeFileList.filter { it.isApk() }
            KEY_OTHER_TYPES -> largeFileList.filter { it.isOther() }
            else -> largeFileList
        }
        val tempList2 = when (filterSize) {
            KEY_SIZE_10_MB -> tempList1.filter { it.size > 1024 * 1024 * 10 }
            KEY_SIZE_50_MB -> tempList1.filter { it.size > 1024 * 1024 * 50 }
            KEY_SIZE_100_MB -> tempList1.filter { it.size > 1024 * 1024 * 100 }
            KEY_SIZE_500_MB -> tempList1.filter { it.size > 1024 * 1024 * 500 }
            KEY_SIZE_1_GB -> tempList1.filter { it.size > 1024 * 1024 * 1024 }
            else -> tempList1
        }
        val tempList3 = when (filterTime) {
            KEY_ALL_TIME -> tempList2
            KEY_1_WEEK -> tempList2.filter {
                val flag = Onaw.isDaysAgo(it.time, 7)

                flag
            }

            KEY_1_MONTH -> tempList2.filter {
                val flag = Onaw.isDaysAgo(it.time, 30)

                flag
            }

            KEY_3_MONTHS -> tempList2.filter { Onaw.isDaysAgo(it.time, 90) }
            KEY_6_MONTHS -> tempList2.filter { Onaw.isDaysAgo(it.time, 180) }
            KEY_1_YEAR -> tempList2.filter { Onaw.isDaysAgo(it.time, 365) }
            else -> tempList2
        }
        adapter.setData(tempList3)
    }

}