package rowedto.jockeyedto.sheetedto.meadowedto.naturaledto.idealedto

import android.annotation.SuppressLint
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.base.datarecovery.R
import com.base.datarecovery.databinding.KeepedtoBinding
import com.base.datarecovery.databinding.PersonedtoBinding
import com.bumptech.glide.Glide
import rowedto.jockeyedto.sheetedto.balsamedto.formaledto.orientationedto.Ambitionedto.inflate
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.SCAN_AUDIOS
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Dynamicedto.SCAN_DOCUMENTS
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Numberedto
import rowedto.jockeyedto.sheetedto.debutedto.revolutionaryedto.Roomedto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Suitcaseedto.toFormatSize
import java.io.File
import java.text.SimpleDateFormat
import java.util.Locale

class Thresholdedto(
    val scanType: Int,
    val select: (all: Boolean, size: Int) -> Unit,
) : RecyclerView.Adapter<Thresholdedto.MCV>() {

    private val beanList = arrayListOf<Numberedto>()
    private var hideThumbnails: Boolean = false
    private var columns: Int = 2

    class MCV(view: View) : ViewHolder(view)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MCV {
        return MCV(R.layout.personedto.inflate(parent))
    }

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

    override fun onBindViewHolder(holder: MCV, position: Int) {
        val binding = PersonedtoBinding.bind(holder.itemView)
        val context = holder.itemView.context
        val bean = beanList[position]
        val file = File(bean.recoveryList.first().path)
        val time = SimpleDateFormat("yyyy-MMM-dd", Locale.getDefault()).format(file.lastModified())
        binding.shorteredto.text = time
        binding.relationshipedto.isSelected = bean.isSelect


        val subAdapter = MediaColumnsAdapter()

        if (scanType == SCAN_DOCUMENTS || scanType == SCAN_AUDIOS) {
            binding.spilledto.layoutManager = LinearLayoutManager(context)
        } else {
            binding.spilledto.layoutManager = GridLayoutManager(context, columns)
            binding.spilledto.layoutParams =
                LinearLayout.LayoutParams(RecyclerView.LayoutParams.WRAP_CONTENT, RecyclerView.LayoutParams.WRAP_CONTENT).apply {
                    topMargin = context.resources.getDimensionPixelOffset(R.dimen.squareedto)
                    gravity = Gravity.CENTER_HORIZONTAL
                }
        }
        binding.spilledto.adapter = subAdapter
        val list = if (hideThumbnails) bean.recoveryList.filter { !it.isThumbnails } else bean.recoveryList
        if (list.isEmpty()) {
            binding.ironedto.visibility = View.GONE
        } else {
            binding.ironedto.visibility = View.VISIBLE
            subAdapter.setData(list)
        }

        binding.relationshipedto.setOnClickListener {
            bean.isSelect = !bean.isSelect
            binding.relationshipedto.isSelected = bean.isSelect
            notifyItemChanged(position)
            itemClick(bean.isSelect, subAdapter)
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    fun setData(data: List<Numberedto>) {
        beanList.clear()
        beanList.addAll(data)
        notifyDataSetChanged()
    }

    inner class MediaColumnsAdapter : RecyclerView.Adapter<MediaColumnsAdapter.CS>() {
        private val list = arrayListOf<Roomedto>()

        inner class CS(view: View) : ViewHolder(view) {
            val iv = view.findViewById<ImageView>(R.id.shiftedto)
            val ivSelector = view.findViewById<ImageView>(R.id.relationshipedto)
            val tvSize = view.findViewById<TextView>(R.id.bulletinedto)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CS {
            var layout = when (columns) {
                2 -> R.layout.slapedto
                3 -> R.layout.paintedto
                4 -> R.layout.shinningedto
                else -> R.layout.slapedto
            }
            if ((scanType == SCAN_DOCUMENTS) || (scanType == SCAN_AUDIOS)) {
                layout = R.layout.keepedto
            }
            return CS(layout.inflate(parent))
        }

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

        override fun onBindViewHolder(holder: CS, position: Int) {
        }

        override fun onBindViewHolder(holder: CS, position: Int, payloads: MutableList<Any>) {

            val context = holder.itemView.context
            val data = list[position]

            if ((scanType == SCAN_DOCUMENTS) or (scanType == SCAN_AUDIOS)) {
                if (payloads.isEmpty()) {
                    val binding = KeepedtoBinding.bind(holder.itemView)
                    binding.relationshipedto.isSelected = data.isSelect
                    val icon = when (data.type) {
                        "PDF" -> R.mipmap.cynosureedto
                        "DOC" -> R.mipmap.economistedto
                        "XLS" -> R.mipmap.bendedto
                        "PPT" -> R.mipmap.hayedto
                        "MP3" -> R.mipmap.stomachedto
                        "WAV" -> R.mipmap.flooredto
                        "FLAC" -> R.mipmap.obtainedto
                        else -> 0
                    }
                    binding.cropedto.setImageResource(icon)
                    val file = File(data.path)
                    binding.glassesedto.text = file.name
                    val time = SimpleDateFormat("MMM-dd-yyyy", Locale.getDefault()).format(file.lastModified())
                    val size = file.length().toFormatSize()
                    val info = "$time $size"
                    binding.giantedto.text = info
                    binding.root.setOnClickListener {
                        data.isSelect = !data.isSelect
                        holder.ivSelector.isSelected = data.isSelect
                        notifyItemChanged(position, "asdada")
                        subItemClick(data)
                    }
                } else {
                    holder.ivSelector.isSelected = data.isSelect
                    super.onBindViewHolder(holder, position, payloads)
                }

            } else {
                if (payloads.isEmpty()) {
                    Glide.with(context).asBitmap().load(data.path).centerCrop().into(holder.iv)
                    holder.ivSelector.isSelected = data.isSelect
                    holder.itemView.setOnClickListener {
                        data.isSelect = !data.isSelect
                        holder.ivSelector.isSelected = data.isSelect
                        notifyItemChanged(position, "changeIv")

                        subItemClick(data)
                    }
                    val file = File(data.path)
                    holder.tvSize.text = file.length().toFormatSize()
                } else {
                    holder.ivSelector.isSelected = data.isSelect
                    super.onBindViewHolder(holder, position, payloads)
                }
            }

        }

        @SuppressLint("NotifyDataSetChanged")
        fun setData(bean: List<Roomedto>) {
            list.clear()
            list.addAll(bean)
            notifyDataSetChanged()
        }

        @SuppressLint("NotifyDataSetChanged")
        fun toggleSelect(select: Boolean) {
            list.forEach {
                it.isSelect = select
            }
            notifyDataSetChanged()
        }


    }

    @SuppressLint("NotifyDataSetChanged")
    fun subItemClick(data: Roomedto) {
        val folderBean = beanList.find { it.recoveryList.contains(data) }

        folderBean?.let { folder ->
            val select = folder.recoveryList.all { it.isSelect }
            if (folder.isSelect != select) {
                folder.isSelect = select
                notifyDataSetChanged()
            }
        }
        val all = beanList.all { it.isSelect }
        val size = beanList.sumOf { it.recoveryList.filter { bean -> bean.isSelect }.size }
        select.invoke(all, size)
    }

    private fun itemClick(isSelect: Boolean, subAdapter: MediaColumnsAdapter) {
        subAdapter.toggleSelect(isSelect)

        val all = beanList.all { it.isSelect }
        val size = beanList.sumOf { it.recoveryList.filter { bean -> bean.isSelect }.size }
        select.invoke(all, size)
    }

    @SuppressLint("NotifyDataSetChanged")
    fun toggleThumbnails(hideThumbnails: Boolean) {
        this.hideThumbnails = hideThumbnails
        notifyDataSetChanged()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun toggleAllSelect(selected: Boolean) {
        beanList.forEach {
            it.isSelect = selected
            it.recoveryList.forEach { bean -> bean.isSelect = selected }
        }
        notifyDataSetChanged()
        val all = beanList.all { it.isSelect }
        val size = beanList.sumOf { it.recoveryList.filter { bean -> bean.isSelect }.size }
        select.invoke(all, size)
    }

    @SuppressLint("NotifyDataSetChanged")
    fun changeColumns(columns: Int) {
        this.columns = columns
        notifyDataSetChanged()
    }

    fun getSelectData(): List<Roomedto> {
        return beanList.flatMap { it.recoveryList }.filter { it.isSelect }
    }
}