package rallyedto.finishedto.biggestedto.canedto.greenedto

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.ContraryedtoBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import rallyedto.battleedto.acresedto.Fireplaceedto.toFormatTime
import rallyedto.battleedto.acresedto.Lemonedto
import rallyedto.dumpedto.editionedto.Failededto
import rallyedto.dumpedto.editionedto.Toothedto
import rallyedto.farewelledto.Technologyedto.showRecoveringDialog
import rallyedto.policeedto.huntedto.Desertedto
import rallyedto.policeedto.huntedto.Drewedto
import rallyedto.policeedto.huntedto.Mediumedto
import rallyedto.policeedto.huntedto.Snuggleedto.SCAN_AUDIOS
import rallyedto.policeedto.huntedto.Snuggleedto.SCAN_DOCUMENTS
import rallyedto.policeedto.huntedto.Snuggleedto.SCAN_PHOTOS
import rallyedto.policeedto.huntedto.Snuggleedto.SCAN_VIDEOS
import rallyedto.talledto.blewedto.Computeredto.isWithinOneMonth
import rallyedto.talledto.blewedto.Computeredto.isWithinSixMonths
import rallyedto.talledto.blewedto.Computeredto.isWithinTwentyFourMonths
import rallyedto.talledto.blewedto.Islandedto
import java.io.File

class Dragonedto : Lemonedto<ContraryedtoBinding>() {

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

    private lateinit var adapter: Toothedto
    private lateinit var filterAdapter: Failededto


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

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


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

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

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

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

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

            SCAN_AUDIOS -> {
                binding.housingedto.visibility = View.GONE
                binding.monstrousedto.visibility = View.GONE
            }

        }
        adapter = Toothedto(scanType,
            select = { all, size ->
                binding.cathodeedto.isSelected = all
                binding.readeredto.text = "Recover($size)"
                binding.readeredto.isEnabled = size > 0
            })
        binding.autonomyedto.adapter = adapter

        filterAdapter = Failededto { bean ->
            filterDismiss(bean)
        }
        binding.quietedto.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.passageedto.text = "Hide thumbnails (${size})"
        }
    }

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

    override fun initListener() {
        binding.gripedto.setOnClickListener {
            filterDismiss()
        }
        binding.unfortunateedto.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            finish()
        }
        binding.chanceedto.setOnCheckedChangeListener { buttonView, isChecked ->
            adapter.toggleThumbnails(isChecked)
        }
        binding.ejectedto.setOnClickListener {
            binding.cathodeedto.isSelected = !binding.cathodeedto.isSelected
            adapter.toggleAllSelect(binding.cathodeedto.isSelected)
        }
        binding.conspiracyedto.setOnClickListener {
            showFilter(it.id)
        }
        binding.copyrightedto.setOnClickListener {
            showFilter(it.id)
        }
        binding.monstrousedto.setOnClickListener {
            showFilter(it.id)
        }
        binding.readeredto.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.paralleledto)
            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, Stitchedto::class.java).apply {
                putExtra("Number", list.size)
                putExtra("ScanType", scanType)
            })
        })
    }

    private fun showFilter(filter: Int) {

        if (!binding.gripedto.isVisible) {
            binding.gripedto.isVisible = true
            binding.massedto.background = ContextCompat.getDrawable(this, R.drawable.nounedto)
        }

        if (filter == R.id.conspiracyedto) {
            binding.beamedto.setImageResource(R.mipmap.climbedto)
            filterAdapter.setData(dateFilterList)
        } else {
            binding.beamedto.setImageResource(R.mipmap.castedto)
        }
        if (filter == R.id.copyrightedto) {
            binding.oneedto.setImageResource(R.mipmap.climbedto)
            filterAdapter.setData(sizeFilterList)
        } else {
            binding.oneedto.setImageResource(R.mipmap.castedto)
        }
        if (filter == R.id.monstrousedto) {
            binding.earnedto.setImageResource(R.mipmap.climbedto)
            filterAdapter.setData(layoutFilterList)
        } else {
            binding.earnedto.setImageResource(R.mipmap.castedto)
        }
    }

    private fun filterDismiss(recoveryFilterBean: Drewedto? = null) {
        binding.gripedto.isVisible = false
        binding.massedto.background = ContextCompat.getDrawable(this, R.drawable.clashedto)
        binding.beamedto.setImageResource(R.mipmap.castedto)
        binding.oneedto.setImageResource(R.mipmap.castedto)
        binding.earnedto.setImageResource(R.mipmap.castedto)

        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<Desertedto>>()

        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<Mediumedto>()
        hash.forEach { (key, value) ->
            list.add(Mediumedto(time = key, recoveryList = value))
        }
        launch(Dispatchers.Main) {
            adapter.setData(list)
        }
    }

    private fun dateFilter(recoveryBean: Desertedto): 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: Desertedto): 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: Mediumedto? = Mediumedto()
    }

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