package io.omido.tabrizonline.base
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.databinding.library.baseAdapters.BR
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
abstract class BaseAdapter<T>(diffCallback: DiffUtil.ItemCallback<T>) :
ListAdapter<T, BaseAdapter<T>.DataBindingViewHolder>(diffCallback) {
private var onItemClicked: ((T, View) -> Unit)? = null
private var onItemLongClicked: ((T, View) -> Unit)? = null
fun setOnItemClicked(onItemClicked: (T, View) -> Unit) {
this.onItemClicked = onItemClicked
}
fun setOnItemLongClicked(onItemLongClicked: (T, View) -> Unit) {
this.onItemLongClicked = onItemLongClicked
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DataBindingViewHolder {
return DataBindingViewHolder(
DataBindingUtil.inflate<ViewDataBinding>(
LayoutInflater.from(parent.context),
viewType,
parent,
false
)
)
}
override fun submitList(list: MutableList<T>?) {
super.submitList(if (list != null) ArrayList<T>(list).toMutableList() else null)
}
override fun onBindViewHolder(holder: DataBindingViewHolder, position: Int) =
holder.bind(getItem(position))
abstract override fun getItemViewType(position: Int): Int
inner class DataBindingViewHolder(private val binding: ViewDataBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: T) {
binding.apply {
setVariable(BR.item, item)
executePendingBindings()
root.apply {
setOnClickListener {
onItemClicked?.invoke(item, this)
}
setOnLongClickListener {
onItemLongClicked?.invoke(item, this)
return@setOnLongClickListener true
}
}
}
}
}
}