package com.webtoonviewer.ui.adapter

import android.graphics.Bitmap
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.webtoonviewer.R

class ImageAdapter(
    private var images: MutableList<Bitmap>,
    private val onClick: () -> Unit,
) : RecyclerView.Adapter<ImageAdapter.ImageViewHolder>() {

    class ImageViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val imageView: ImageView = view.findViewById(R.id.imageViewImageItem)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_image, parent, false)
        return ImageViewHolder(view)
    }

    override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
        holder.imageView.setImageBitmap(images[position])
        holder.itemView.setOnClickListener {
            onClick()
        }
    }

    override fun getItemCount(): Int = images.size

    fun initImages() {
        images.clear()
    }

    fun addImage(bitmap: Bitmap) {
        images.add(bitmap)
        notifyItemInserted(images.size - 1)
    }

    fun updateImages(bitmaps: List<Bitmap>) {
        initImages()
        images.addAll(bitmaps)
        notifyDataSetChanged()
    }
}