package com.base.filerecoveryrecyclebin.adapter

import android.annotation.SuppressLint
import android.text.format.Formatter
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.base.filerecoveryrecyclebin.R
import com.base.filerecoveryrecyclebin.bean.MediaBean
import com.base.filerecoveryrecyclebin.databinding.ItemLargeFileBinding
import com.base.filerecoveryrecyclebin.utils.LogEx
import com.base.filerecoveryrecyclebin.view.XmlEx.inflate

class LargeFileAdapter(
    val itemClick: (data: MediaBean) -> Unit,
    val selectClick: (selectList: List<MediaBean>) -> Unit
) : Adapter<LargeFileAdapter.UUU>() {
    private val TAG = "BigFileAdapter"

    private val files = arrayListOf<MediaBean>()

    class UUU(view: View) : ViewHolder(view) {

    }

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

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

    override fun onBindViewHolder(holder: UUU, position: Int) {

    }

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

        val binding = ItemLargeFileBinding.bind(holder.itemView)
        val data = files[position]
        val content = holder.itemView.context


        if (payloads.isEmpty()) {

            binding.tvName.text = data.path.substring(data.path.lastIndexOf("/") + 1)
            binding.tvSize.text = Formatter.formatFileSize(content, data.size)
            binding.root.setOnClickListener {
                itemClick.invoke(data)
            }
            binding.ivSelector.isSelected = data.isSelect
            binding.flSelect.setOnClickListener {
                data.isSelect = !data.isSelect
                binding.ivSelector.isSelected = data.isSelect
                notifyItemChanged(position, "dasds")
                val selectList = files.filter { it.isSelect }
                selectClick.invoke(selectList)
            }
        } else {
            binding.ivSelector.isSelected = data.isSelect
            super.onBindViewHolder(holder, position, payloads)
        }

    }

    @SuppressLint("NotifyDataSetChanged")
    fun setData(bigFileList: List<MediaBean>) {
        bigFileList.forEach {
            LogEx.logDebug(TAG, "$it")
        }
        files.clear()
        files.addAll(bigFileList)
        files.sortByDescending { it.size }
        notifyDataSetChanged()
    }

    fun getSelectData(): List<MediaBean> {
        return files.filter { it.isSelect }
    }

    @SuppressLint("NotifyDataSetChanged")
    fun removeData(deleteList: List<MediaBean>) {
        files.removeAll(deleteList.toSet())
        notifyDataSetChanged()
    }

    fun isEmpty(): Boolean {
        return files.isEmpty()
    }
}