package com.sketch.ar.artdrawing.utils

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

abstract class BaseAdapter<K, T : ViewBinding?>(protected var mContext: Context) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    protected var data: MutableList<K> = ArrayList()

    var isLoadingAdded = false
        protected set


    fun addData(data: List<K>?) {
        this.data.addAll(data!!)
        notifyDataSetChanged()
    }

    fun updateData(data: List<K>?) {
        this.data.clear()
        this.data.addAll(data!!)
        notifyDataSetChanged()
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val viewBinding = getViewBinding(parent)
        return VHolder(viewBinding)
    }

    protected abstract fun getViewBinding(parent: ViewGroup?): T
    override fun getItemViewType(position: Int): Int {
        return if (position == data.size && isLoadingAdded) TYPE_FOOTER else TYPE_ITEM
    }

    override fun getItemCount(): Int {
        return data.size + if (isLoadingAdded) 1 else 0
    }

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

    companion object {
        protected const val TYPE_ITEM = 0
        protected const val TYPE_FOOTER = 1
    }
}