package com.pan_american.android.base

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.pan_american.android.OASystem

class ListAdapter<T> private constructor(): RecyclerView.Adapter<ListAdapter<T>.ViewHolder>() {

    //数据
    private lateinit var itemList: List<T>
    //布局ID
    private  var layoutId: Int = 0
    //绑定事件的lambda
    private lateinit var addBindView:((itemView: View, item: T) -> Unit)

    lateinit var onRecyclerViewItemClick: OnRecyclerViewItemClick<T>

    inner class ViewHolder(view: View): RecyclerView.ViewHolder(view)

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

        return ViewHolder(view)
    }

    override fun getItemCount() = itemList.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        addBindView.invoke(holder.itemView, itemList[position])

        holder.itemView.setOnClickListener {
            onRecyclerViewItemClick.onItemClick(position)
        }
    }

    interface OnRecyclerViewItemClick<T> {
        fun onItemClick(position: Int)
    }

    class Builder<B> {

        private var adapter: ListAdapter<B> = ListAdapter()

        /**
         * 设置数据
         */
        fun setData(itemList: List<B>): Builder<B> {
            adapter.itemList = itemList
            return this
        }

        /**
         * 设置布局ID
         */
        fun setLayoutId(layoutId: Int): Builder<B> {
            adapter.layoutId = layoutId
            return this
        }

        /**
         * 绑定view和数据
         */
        fun addBindView(bindView: ((itemView: View, data: B) -> Unit)): Builder<B> {
            adapter.addBindView = bindView
            return this
        }

        fun create(): ListAdapter<B> {
            return adapter
        }
    }
}
