package importantedto.appliededto.surgeonedto.promiseedto.freedomedto

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.DilemmaedtoBinding
import importantedto.afteredto.constitutionaledto.Constraintedto.toFormatTime
import importantedto.afteredto.constitutionaledto.Murderedto
import importantedto.concreteedto.cameedto.Absenceedto
import importantedto.concreteedto.cameedto.Changingedto
import importantedto.concreteedto.cameedto.Hateedto.SCAN_AUDIOS
import importantedto.concreteedto.cameedto.Hateedto.SCAN_DOCUMENTS
import importantedto.concreteedto.cameedto.Hateedto.SCAN_PHOTOS
import importantedto.concreteedto.cameedto.Hateedto.SCAN_VIDEOS
import importantedto.concreteedto.cameedto.Plainedto
import importantedto.deserveedto.manufactureredto.viableedto.Equaledto
import importantedto.deserveedto.manufactureredto.viableedto.Swearedto
import importantedto.gallonedto.Passedto.isWithinOneMonth
import importantedto.gallonedto.Passedto.isWithinSixMonths
import importantedto.gallonedto.Passedto.isWithinTwentyFourMonths
import importantedto.gallonedto.Transcendedto
import importantedto.maidedto.witnessedto.nationalismedto.Photocopyedto.showRecoveringDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

class Flingedto : Murderedto<DilemmaedtoBinding>() {

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

    private lateinit var adapter: Equaledto
    private lateinit var filterAdapter: Swearedto


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

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


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

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

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

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

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

            SCAN_AUDIOS -> {
                binding.studentedto.visibility = View.GONE
                binding.possibleedto.visibility = View.GONE
            }

        }
        adapter = Equaledto(scanType,
            select = { all, size ->
                binding.saltedto.isSelected = all
                binding.basketedto.text = "Recover($size)"
                binding.basketedto.isEnabled = size > 0
            })
        binding.questedto.adapter = adapter

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

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

    override fun initListener() {
        binding.accompanyedto.setOnClickListener {
            filterDismiss()
        }
        binding.bangedto.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            finish()
        }
        binding.assetedto.setOnCheckedChangeListener { buttonView, isChecked ->
            adapter.toggleThumbnails(isChecked)
        }
        binding.sunshineedto.setOnClickListener {
            binding.saltedto.isSelected = !binding.saltedto.isSelected
            adapter.toggleAllSelect(binding.saltedto.isSelected)
        }
        binding.constituencyedto.setOnClickListener {
            showFilter(it.id)
        }
        binding.suggestedto.setOnClickListener {
            showFilter(it.id)
        }
        binding.possibleedto.setOnClickListener {
            showFilter(it.id)
        }
        binding.basketedto.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.kettleedto)
            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, Fourthedto::class.java).apply {
                putExtra("Number", list.size)
                putExtra("ScanType", scanType)
            })
        })
    }

    private fun showFilter(filter: Int) {

        if (!binding.accompanyedto.isVisible) {
            binding.accompanyedto.isVisible = true
            binding.resourceedto.background = ContextCompat.getDrawable(this, R.drawable.negotiationedto)
        }

        if (filter == R.id.constituencyedto) {
            binding.transformedto.setImageResource(R.mipmap.electronedto)
            filterAdapter.setData(dateFilterList)
        } else {
            binding.transformedto.setImageResource(R.mipmap.performeredto)
        }
        if (filter == R.id.suggestedto) {
            binding.createedto.setImageResource(R.mipmap.electronedto)
            filterAdapter.setData(sizeFilterList)
        } else {
            binding.createedto.setImageResource(R.mipmap.performeredto)
        }
        if (filter == R.id.possibleedto) {
            binding.fasteredto.setImageResource(R.mipmap.electronedto)
            filterAdapter.setData(layoutFilterList)
        } else {
            binding.fasteredto.setImageResource(R.mipmap.performeredto)
        }
    }

    private fun filterDismiss(recoveryFilterBean: Plainedto? = null) {
        binding.accompanyedto.isVisible = false
        binding.resourceedto.background = ContextCompat.getDrawable(this, R.drawable.coatedto)
        binding.transformedto.setImageResource(R.mipmap.performeredto)
        binding.createedto.setImageResource(R.mipmap.performeredto)
        binding.fasteredto.setImageResource(R.mipmap.performeredto)

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

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

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

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