package com.all.pdfreader.pro.app.ui.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.all.pdfreader.pro.app.databinding.AdapterSplitSelectedPageItemBinding
import com.all.pdfreader.pro.app.model.PdfSelectedPagesItem
import com.all.pdfreader.pro.app.util.AppUtils.dpToPx
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import java.io.File

class SplitSelectedPdfAdapter(
    private val list: MutableList<PdfSelectedPagesItem>,
    private val onEditClick: (PdfSelectedPagesItem, Int) -> Unit,
    private val onDeleteClick: (PdfSelectedPagesItem, Int) -> Unit
) : RecyclerView.Adapter<SplitSelectedPdfAdapter.PdfViewHolder>() {

    inner class PdfViewHolder(val binding: AdapterSplitSelectedPageItemBinding) :
        RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = PdfViewHolder(
        AdapterSplitSelectedPageItemBinding.inflate(
            LayoutInflater.from(parent.context), parent, false
        )
    )

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: PdfViewHolder, position: Int) {
        val item = list[position]
        holder.binding.tvPages.text = item.selectedPageNumbersString()
        val thumbPath = item.getFirstThumbPath()
        if (thumbPath.isNotEmpty()) {
            Glide.with(holder.binding.root).load(File(thumbPath))
                .transform(CenterCrop(), RoundedCorners(4.dpToPx(holder.binding.root.context)))
                .into(holder.binding.tvFileImg)
        }
        holder.binding.tvFileName.text = item.fileName
        holder.binding.editTitleBtn.setOnClickListener {
            val pos = holder.bindingAdapterPosition
            onEditClick(item, pos)
        }
        holder.binding.deleteBtn.setOnClickListener {
            val pos = holder.bindingAdapterPosition
            onDeleteClick(item, pos)
        }
    }

    override fun getItemCount(): Int = list.size

    @SuppressLint("NotifyDataSetChanged")
    fun updateAdapter() {
        notifyDataSetChanged()
    }

    fun updateItem(position: Int) = notifyItemChanged(position)

    fun removeItem(position: Int) = notifyItemRemoved(position)
}
