package com.zxhy.hfilemanagermaster.files

import android.annotation.SuppressLint
import android.net.Uri
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.hfilemanagermaster.R
import com.example.hfilemanagermaster.databinding.ItemImageBinding
import com.zxhy.hfilemanagermaster.knife.getFilePathByUri
import com.zxhy.hfilemanagermaster.knife.inflate
import java.io.File

class ImageSelectAdapter(private val action: (file: File) -> Unit) :
    RecyclerView.Adapter<ImageSelectAdapter.ImageViewHolder>() {

    private val imageList = arrayListOf<Uri>()

    class ImageViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val binding = ItemImageBinding.bind(view)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {
        val root = R.layout.item_image.inflate(parent)
        return ImageViewHolder(root)
    }

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

    override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
        val context = holder.binding.root.context
        val data = imageList[position]
        holder.binding.iv.setImageURI(data)
        holder.binding.root.setOnClickListener {
            val path = getFilePathByUri(context, data)?:""
            action.invoke(File(path))
        }
    }


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