package com.zxhyis.toolss.ui.adapter

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



open class CommonAdapter<T> constructor(
    private val layoutId: Int,
    private val dataList: ArrayList<T>,
    private val bindHolder: View.(T) -> Unit
) : RecyclerView.Adapter<CommonAdapter.ViewHolder>() {

    private var itemClick: T.() -> Unit = {}

    fun updateItem(position: Int, newItem: T) {
        if (position >= 0 && position < dataList.size) {
            dataList[position] = newItem
            notifyItemChanged(position)
        }
    }

    constructor(layoutId: Int,
                itemList: ArrayList<T>,
                bindHolder: View.(T) -> Unit,
                itemClick: T.() -> Unit = {}) : this(layoutId,itemList, bindHolder) {
                this.itemClick = itemClick
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView=LayoutInflater.from(parent.context).inflate(layoutId,parent,false)
        return ViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val type=dataList[position]
        holder.itemView.bindHolder(type)
        holder.itemView.setOnClickListener {
            itemOnClick(it,position)
        }
    }

    override fun getItemCount()=dataList.size

    open fun itemOnClick(itemView: View,position: Int){
        dataList[position].itemClick()
    }
}
