package com.zxhy.hfilemanagermaster.files

import android.annotation.SuppressLint
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.hfilemanagermaster.R
import com.example.hfilemanagermaster.databinding.ItemImageBinding

class ImageAdapter : RecyclerView.Adapter<ImageAdapter.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)
    }

    /**
     * 解析xml布局
     *
     * @param parent 父布局
     * @param attachToRoot 是否依附到父布局
     */
    fun Int.inflate(parent: ViewGroup, attachToRoot: Boolean = false): View {
        return LayoutInflater.from(parent.context).inflate(this, parent, attachToRoot)
    }

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