package com.pan_american.android.base

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

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

    //数据
    private lateinit var itemList: List<T>

    //布局ID
    private var layoutId = 0

    //绑定事件的lambda
    private lateinit var addBindView: ((itemView: View, item: T) -> Unit)

    //是否有删除权限
    private var canDelete = false

    lateinit var onRecyclerViewItemClick: OnRecyclerViewItemClick<T>

    inner class ViewHolder(view: View): RecyclerView.ViewHolder(view) {
        val deleteButton: ImageView = view.findViewById(R.id.delete)
    }

    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])

        if (!canDelete) {
            holder.deleteButton.visibility = View.GONE
        }

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

        holder.deleteButton.setOnClickListener {
            onRecyclerViewItemClick.onItemDelete(position)
        }
    }

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

    class Builder<B> {
        private var adapter: CardAdapter<B> = CardAdapter()

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

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

        /**
         * 是否有删除权限
         */
        fun setCanDelete(canDelete: Boolean): Builder<B> {
            adapter.canDelete = canDelete
            return this
        }

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

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