package com.xyzshell.myphoneinfo.base

import android.content.Context
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding

abstract class BaseAdapter<K, T : ViewBinding>(
    protected val mContext: Context
) : RecyclerView.Adapter<BaseAdapter.VHolder<T>>() {

    protected val data: MutableList<K> = mutableListOf()

    fun addData(items: List<K>?) {
        items?.let {
            val start = data.size
            data.addAll(it)
            notifyItemRangeInserted(start, it.size)
        }
    }

    fun setData(items: List<K>?) {
        data.clear()
        items?.let { data.addAll(it) }
        notifyDataSetChanged()
    }


    override fun getItemCount(): Int = data.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VHolder<T> {
        return VHolder(getViewBinding(parent))
    }

    override fun onBindViewHolder(holder: VHolder<T>, position: Int) {
        bindItem(holder, data[position])
    }


    protected abstract fun getViewBinding(parent: ViewGroup): T
    protected abstract fun bindItem(holder: VHolder<T>, item: K)


    class VHolder<V : ViewBinding>(val vb: V) : RecyclerView.ViewHolder(vb.root)
}
