package com.base.filerecoveryrecyclebin.activity.recovery

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.filerecoveryrecyclebin.R
import com.base.filerecoveryrecyclebin.adapter.FileTimeColumnsAdapter
import com.base.filerecoveryrecyclebin.adapter.RecoveryFilterAdapter
import com.base.filerecoveryrecyclebin.bean.ConstObject.SCAN_AUDIOS
import com.base.filerecoveryrecyclebin.bean.ConstObject.SCAN_DOCUMENTS
import com.base.filerecoveryrecyclebin.bean.ConstObject.SCAN_PHOTOS
import com.base.filerecoveryrecyclebin.bean.ConstObject.SCAN_VIDEOS
import com.base.filerecoveryrecyclebin.bean.FolderBean
import com.base.filerecoveryrecyclebin.bean.RecoveryBean
import com.base.filerecoveryrecyclebin.bean.RecoveryFilterBean
import com.base.filerecoveryrecyclebin.databinding.ActivityFileRecoveryBinding
import com.base.filerecoveryrecyclebin.help.BaseActivity
import com.base.filerecoveryrecyclebin.help.KotlinExt.toFormatTime
import com.base.filerecoveryrecyclebin.utils.BarUtils
import com.base.filerecoveryrecyclebin.utils.TimeUtils.isWithinOneMonth
import com.base.filerecoveryrecyclebin.utils.TimeUtils.isWithinSixMonths
import com.base.filerecoveryrecyclebin.utils.TimeUtils.isWithinTwentyFourMonths
import com.base.filerecoveryrecyclebin.view.DialogViews.showRecoveringDialog
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File

class FileRecoveryActivity : BaseActivity<ActivityFileRecoveryBinding>() {

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

    private lateinit var adapter: FileTimeColumnsAdapter
    private lateinit var filterAdapter: RecoveryFilterAdapter


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

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


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

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

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

            SCAN_DOCUMENTS -> {
                binding.clThumbnails.visibility = View.GONE
                binding.llLayout.visibility = View.GONE
            }

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

            SCAN_AUDIOS -> {
                binding.clThumbnails.visibility = View.GONE
                binding.llLayout.visibility = View.GONE
            }

        }
        adapter = FileTimeColumnsAdapter(scanType,
            select = { all, size ->
                binding.ivSelectAll.isSelected = all
                binding.tvRecover.text = "Recover($size)"
                binding.tvRecover.isEnabled = size > 0
            })
        binding.rv.adapter = adapter

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

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

    override fun initListener() {
        binding.llFilter.setOnClickListener {
            filterDismiss()
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        onBackPressedDispatcher.addCallback {
            finish()
        }
        binding.switchThumbnails.setOnCheckedChangeListener { buttonView, isChecked ->
            adapter.toggleThumbnails(isChecked)
        }
        binding.flSelectAll.setOnClickListener {
            binding.ivSelectAll.isSelected = !binding.ivSelectAll.isSelected
            adapter.toggleAllSelect(binding.ivSelectAll.isSelected)
        }
        binding.llDate.setOnClickListener {
            showFilter(it.id)
        }
        binding.llSize.setOnClickListener {
            showFilter(it.id)
        }
        binding.llLayout.setOnClickListener {
            showFilter(it.id)
        }
        binding.tvRecover.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.app_name).replace("/", " ")
            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, FileRecoveredActivity::class.java).apply {
                putExtra("Number", list.size)
                putExtra("ScanType", scanType)
            })
        })
    }

    private fun showFilter(filter: Int) {

        if (!binding.llFilter.isVisible) {
            binding.llFilter.isVisible = true
            binding.clTop.background = ContextCompat.getDrawable(this, R.drawable.bg_e7ecff_edf5ff)
        }

        if (filter == R.id.ll_date) {
            binding.ivDate.setImageResource(R.mipmap.zhankai)
            filterAdapter.setData(dateFilterList)
        } else {
            binding.ivDate.setImageResource(R.mipmap.shouqi)
        }
        if (filter == R.id.ll_size) {
            binding.ivSize.setImageResource(R.mipmap.zhankai)
            filterAdapter.setData(sizeFilterList)
        } else {
            binding.ivSize.setImageResource(R.mipmap.shouqi)
        }
        if (filter == R.id.ll_layout) {
            binding.ivLayout.setImageResource(R.mipmap.zhankai)
            filterAdapter.setData(layoutFilterList)
        } else {
            binding.ivLayout.setImageResource(R.mipmap.shouqi)
        }
    }

    private fun filterDismiss(recoveryFilterBean: RecoveryFilterBean? = null) {
        binding.llFilter.isVisible = false
        binding.clTop.background = ContextCompat.getDrawable(this, R.drawable.bg_e7ecff_edf5ff_blr15)
        binding.ivDate.setImageResource(R.mipmap.shouqi)
        binding.ivSize.setImageResource(R.mipmap.shouqi)
        binding.ivLayout.setImageResource(R.mipmap.shouqi)

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

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

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

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

}