package rowedto.jockeyedto.sheetedto.atticedto.strainedto.wolfedto.furtheredto

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Environment
import android.view.View
import androidx.activity.addCallback
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.base.datarecovery.R
import com.base.datarecovery.databinding.PostureedtoBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import rowedto.jockeyedto.sheetedto.balsamedto.formaledto.orientationedto.Patedto.showRecoveringDialog
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.SCAN_AUDIOS
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.SCAN_DOCUMENTS
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.SCAN_PHOTOS
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.SCAN_VIDEOS
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Numberedto
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Roomedto
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Treatedto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Crossingedto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Suitcaseedto.toFormatTime
import rowedto.jockeyedto.sheetedto.meadowedto.naturaledto.idealedto.Noiseedto
import rowedto.jockeyedto.sheetedto.meadowedto.naturaledto.idealedto.Thresholdedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Burnedto.isWithinOneMonth
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Burnedto.isWithinSixMonths
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Burnedto.isWithinTwentyFourMonths
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Spareedto
import java.io.File

class Attackedto : Crossingedto<PostureedtoBinding>() {

    private var scanType = 0
    override val binding: PostureedtoBinding by lazy {
        PostureedtoBinding.inflate(layoutInflater)
    }

    private lateinit var adapter: Thresholdedto
    private lateinit var filterAdapter: Noiseedto


    private val dateFilterList = arrayListOf(
        Treatedto("All", "Size", true),
        Treatedto("With 1 month", "Date"),
        Treatedto("With 6 months", "Date"),
        Treatedto("With 24 months", "Date"),
    )
    private var sizeFilterList = arrayListOf(
        Treatedto("All", "Size", true),
        Treatedto("0 - 1 M", "Size"),
        Treatedto("1 - 5 M", "Size"),
        Treatedto("> 5 M", "Size"),
    )

    private val layoutFilterList = arrayListOf(
        Treatedto("2 columns", "Layout", true),
        Treatedto("3 columns", "Layout"),
        Treatedto("4 columns", "Layout"),
    )


    @SuppressLint("SetTextI18n")
    override fun initView() {
        Spareedto.setStatusBarLightMode(this, true)
        Spareedto.setStatusBarColor(this, Color.TRANSPARENT)

        scanType = intent.extras?.getInt("ScanType") ?: 0

        when (scanType) {
            SCAN_PHOTOS -> {
                setThumbnails()
            }

            SCAN_DOCUMENTS -> {
                binding.possibilityedto.visibility = View.GONE
            }

            SCAN_VIDEOS -> {
                binding.possibilityedto.visibility = View.GONE
            }

            SCAN_AUDIOS -> {
                binding.possibilityedto.visibility = View.GONE
                binding.formatedto.visibility = View.GONE
            }

        }
        adapter = Thresholdedto(scanType,
            select = { all, size ->
                binding.captureedto.isSelected = all
                binding.schemeedto.text = "Recover($size)"
                binding.schemeedto.isEnabled = size > 0
            })
        binding.funeraledto.adapter = adapter

        filterAdapter = Noiseedto { bean ->
            filterDismiss(bean)
        }
        binding.brimstoneedto.adapter = filterAdapter
        initData()
    }

    @SuppressLint("SetTextI18n")
    private fun setThumbnails() = lifecycleScope.launch(Dispatchers.IO) {

        var size = 0
        folderBean?.recoveryList?.forEach { bean ->
            runCatching {
                val bitmap: Bitmap? = BitmapFactory.decodeFile(bean.path)
                bitmap?.let {
                    if (it.height < 256 || it.width < 256) {
                        size++
                        bean.isThumbnails = true
                    }
                }
            }
        }
        launch(Dispatchers.Main) {
            binding.legislatureedto.text = "Hide thumbnails (${size})"
        }
    }

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

    override fun initListener() {
        binding.beltedto.setOnClickListener {
            filterDismiss()
        }
        binding.conditionedto.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            finish()
        }
        binding.artedto.setOnCheckedChangeListener { buttonView, isChecked ->
            adapter.toggleThumbnails(isChecked)
        }
        binding.literacyedto.setOnClickListener {
            binding.captureedto.isSelected = !binding.captureedto.isSelected
            adapter.toggleAllSelect(binding.captureedto.isSelected)
        }
        binding.doubtedto.setOnClickListener {
            showFilter(it.id)
        }
        binding.prayeredto.setOnClickListener {
            showFilter(it.id)
        }
        binding.formatedto.setOnClickListener {
            showFilter(it.id)
        }
        binding.schemeedto.setOnClickListener {
            var dirType = ""
            when (scanType) {
                SCAN_PHOTOS -> dirType = "Photo"
                SCAN_DOCUMENTS -> dirType = "Document"
                SCAN_VIDEOS -> dirType = "Video"
                SCAN_AUDIOS -> dirType = "Audio"
            }
            val appName = this.resources.getString(R.string.overchargeedto)
            val appDir = File(Environment.getExternalStorageDirectory(), appName)
            val dir = File(appDir, dirType)
            if (!dir.exists()) {
                dir.mkdirs()
            }
            beginRecover(dir)
        }
    }

    private fun beginRecover(dir: File) {
        val list = adapter.getSelectData().map { it.path }
        showRecoveringDialog(lifecycleScope, list, dir, copyProgressAction = {

        }, finish = {
            startActivity(Intent(this, Inappropriateedto::class.java).apply {
                putExtra("Number", list.size)
                putExtra("ScanType", scanType)
            })
        })
    }

    private fun showFilter(filter: Int) {

        if (!binding.beltedto.isVisible) {
            binding.beltedto.isVisible = true
            binding.rebellionedto.background = ContextCompat.getDrawable(this, R.drawable.hornedto)
        }

        if (filter == R.id.doubtedto) {
            binding.intentionedto.setImageResource(R.mipmap.earlyedto)
            filterAdapter.setData(dateFilterList)
        } else {
            binding.intentionedto.setImageResource(R.mipmap.wisdomedto)
        }
        if (filter == R.id.prayeredto) {
            binding.jumpedto.setImageResource(R.mipmap.earlyedto)
            filterAdapter.setData(sizeFilterList)
        } else {
            binding.jumpedto.setImageResource(R.mipmap.wisdomedto)
        }
        if (filter == R.id.formatedto) {
            binding.guaranteeedto.setImageResource(R.mipmap.earlyedto)
            filterAdapter.setData(layoutFilterList)
        } else {
            binding.guaranteeedto.setImageResource(R.mipmap.wisdomedto)
        }
    }

    private fun filterDismiss(recoveryFilterBean: Treatedto? = null) {
        binding.beltedto.isVisible = false
        binding.rebellionedto.background = ContextCompat.getDrawable(this, R.drawable.weightedto)
        binding.intentionedto.setImageResource(R.mipmap.wisdomedto)
        binding.jumpedto.setImageResource(R.mipmap.wisdomedto)
        binding.guaranteeedto.setImageResource(R.mipmap.wisdomedto)

        recoveryFilterBean?.let { bean ->
            if (bean.type == "Date") {
                dateFilterList.find { it.isSelect }?.isSelect = false
                dateFilterList.find { it == bean }?.isSelect = true
                initData()
                return
            }
            if (bean.type == "Size") {
                sizeFilterList.find { it.isSelect }?.isSelect = false
                sizeFilterList.find { it == bean }?.isSelect = true
                initData()
                return
            }
            if (bean.type == "Layout") {
                layoutFilterList.find { it.isSelect }?.isSelect = false
                layoutFilterList.find { it == bean }?.isSelect = true

                val index = layoutFilterList.indexOf(bean)
                val columns = when (index) {
                    0 -> 2
                    1 -> 3
                    2 -> 4
                    else -> 2
                }
                adapter.changeColumns(columns)
            }
        }

    }


    private fun initData() = lifecycleScope.launch(Dispatchers.IO) {

        val hash = HashMap<String, ArrayList<Roomedto>>()

        folderBean?.let {
            it.recoveryList.forEach { recoveryBean ->
                if (dateFilter(recoveryBean) && sizeFilter(recoveryBean)) {
                    val file = File(recoveryBean.path)
                    val time = file.lastModified().toFormatTime()
                    if (hash[time].isNullOrEmpty()) {
                        hash[time] = arrayListOf()
                    }
                    hash[time]?.add(recoveryBean)
                }

            }
        }
        val list = arrayListOf<Numberedto>()
        hash.forEach { (key, value) ->
            list.add(Numberedto(time = key, recoveryList = value))
        }
        launch(Dispatchers.Main) {
            adapter.setData(list)
        }
    }

    private fun dateFilter(recoveryBean: Roomedto): Boolean {
        val index = dateFilterList.indexOfFirst { it.isSelect }
        return when (index) {
            1 -> isWithinOneMonth(File(recoveryBean.path).lastModified())
            2 -> isWithinSixMonths(File(recoveryBean.path).lastModified())
            3 -> isWithinTwentyFourMonths(File(recoveryBean.path).lastModified())
            else -> true
        }
    }

    private fun sizeFilter(recoveryBean: Roomedto): Boolean {
        val oneMegabyte = 1024 * 1024L
        val index = sizeFilterList.indexOfFirst { it.isSelect }

        return when (index) {
            1 -> File(recoveryBean.path).length() in 0L..oneMegabyte
            2 -> File(recoveryBean.path).length() in oneMegabyte..oneMegabyte * 5
            3 -> File(recoveryBean.path).length() > oneMegabyte * 5
            else -> true
        }
    }

    companion object {
        var folderBean: Numberedto? = Numberedto()
    }

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