package com.zxhy.solarmasterace.filebrowser

import android.view.View
import android.view.ViewGroup
import coil.load
import com.zxhy.solarmasterace.R
import com.zxhy.solarmasterace.adapter.CommonAdapter
import com.zxhy.solarmasterace.adapter.ItemCardImageSelect100ViewHolder
import com.zxhy.solarmasterace.quicktools.ColiVideoEx
import com.zxhy.solarmasterace.quicktools.inflate

class FileGridAdapter(
    private val selectClick: (flag: Boolean) -> Unit,
    private val itemClick: ((path: String) -> Unit)? = null
) : CommonAdapter<ItemCardImageSelect100ViewHolder>() {
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): ItemCardImageSelect100ViewHolder {
        return ItemCardImageSelect100ViewHolder(R.layout.item_card_image_selector_100.inflate(parent))
    }

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

    }

    override fun onBindViewHolder(
        holder: ItemCardImageSelect100ViewHolder,
        position: Int,
        payloads: MutableList<Any>
    ) {
        val data = fileList[position]
        val context = holder.binding.root.context
        if (payloads.isEmpty()) {
            holder.binding.apply {
                if (data.isImage()) {
                    iv.load(data.file())
                    ivCamera.visibility = View.GONE
                    iv.setOnClickListener {
                        itemClick?.invoke(data.path)
                    }
                } else if (data.isVideo()) {
                    iv.load(data.file(), ColiVideoEx.videoLoader(context))
                    ivCamera.visibility = View.VISIBLE
                    iv.setOnClickListener { }
                }

                ivSelector.isSelected = data.isSelect
                ivSelector.setOnClickListener {
                    data.isSelect = !data.isSelect
                    notifyItemChanged(position, "单条刷新")
                    val flag = fileList.all { it.isSelect }
                    selectClick.invoke(flag)
                }
            }
        } else {

            holder.binding.apply {
                ivSelector.isSelected = data.isSelect
            }

            super.onBindViewHolder(holder, position, payloads)
        }
    }
}