package com.gdtlib.lib.adapter

import android.view.LayoutInflater
import androidx.recyclerview.widget.RecyclerView
import com.gdtlib.lib.viewholder.AbstractViewHolder

/**
 * An abstract class of [RecyclerView.Adapter] to display a list of [T]
 */
abstract class AbstractAdapter<T : Any>(
    protected val inflater: LayoutInflater
) : RecyclerView.Adapter<AbstractViewHolder<T>>(),
    AbstractViewHolder.OnClickListener {

    interface OnItemClickListener<T : Any> {
        fun onItemClick(item: T)

    }

    var listener: OnItemClickListener<T>? = null

    var list: List<T> = ArrayList()
        set(value) {
            if (field.isNotEmpty()) (field as ArrayList).clear()
            (field as ArrayList).addAll(value)
            notifyDataSetChanged()
        }

    fun addList(list: List<T>) {
        if (list.isEmpty()) return
        (this.list as ArrayList).addAll(list)
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: AbstractViewHolder<T>, position: Int) {
        val user = list[position]
        holder.bindView(user)
    }

    override fun onClick(position: Int) {
        listener?.onItemClick(list[position])
    }
}