package com.base.scanqrclear.luma

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding

abstract class BaseAdapter<T, VB : ViewBinding>(
    private var items: List<T> = emptyList()
) : RecyclerView.Adapter<BaseViewHolder<VB>>() {

    interface OnClickCallback<T> {
        fun onClicked(view: View, position: Int, item: T)
    }

    var callback: OnClickCallback<T>? = null

    fun submitList(data: List<T>) {
        items = data
        notifyDataSetChanged()
    }

    fun add(item: T) {
        items = items.toMutableList().apply { add(item) }
        notifyItemInserted(items.size - 1)
    }

    val list: MutableList<T> get() = items.toMutableList()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<VB> {
        return BaseViewHolder(getViewBinding(LayoutInflater.from(parent.context), parent))
    }

    override fun onBindViewHolder(holder: BaseViewHolder<VB>, position: Int) {
        bind(holder, position, items[position])
    }

    override fun getItemCount(): Int = items.size

    abstract fun getViewBinding(layoutInflater: LayoutInflater, parent: ViewGroup): VB

    abstract fun bind(holder: BaseViewHolder<VB>, position: Int, item: T)
}