package com.base.filerecoveryrecyclebin.adapter

import android.annotation.SuppressLint
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.base.filerecoveryrecyclebin.R
import com.base.filerecoveryrecyclebin.bean.MediaBean
import com.base.filerecoveryrecyclebin.view.XmlEx.inflate
import com.bumptech.glide.Glide

class MediaSubAdapter : RecyclerView.Adapter<MediaSubAdapter.Sub>() {

    private val subList: ArrayList<MediaBean> = arrayListOf()

    var subClickAction: (() -> Unit)? = null

    inner class Sub(view: View) : RecyclerView.ViewHolder(view) {
        val iv = view.findViewById<ImageView>(R.id.iv)
        val ivSelector = view.findViewById<ImageView>(R.id.iv_selector)
    }

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

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

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

    }

    override fun onBindViewHolder(holder: Sub, position: Int, payloads: MutableList<Any>) {
        val context = holder.itemView.context
        val data = subList[position]

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

                subClickAction?.invoke()
            }
        } else {
            holder.ivSelector.isSelected = data.isSelect
            super.onBindViewHolder(holder, position, payloads)
        }
    }

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

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

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

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