package com.lukouguoji.module_base.base

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import com.lukouguoji.module_base.interfaces.IOnItemClickListener
import com.lukouguoji.module_base.ktx.loge
import kotlin.properties.Delegates

class CommonAdapter(
    val context: Context,
    private val layoutId: Int,
    private val viewHolderClass: Class<out BaseViewHolder<*, out ViewDataBinding>>
) : RecyclerView.Adapter<BaseViewHolder<*, out ViewDataBinding>>(), IOnItemClickListener {

    private var inflater: LayoutInflater by Delegates.notNull()

    // 列表数据
    var items: ArrayList<Any> = arrayListOf()

    init {
        inflater = LayoutInflater.from(context)
    }

    //条目点击监听列表
    private val _itemClickListenerList = arrayListOf<IOnItemClickListener>()

    /**
     * 刷新数据
     */
    fun refresh(list: List<out Any>?) {
        items.clear()
        items.addAll(list ?: emptyList())
        notifyDataSetChanged()
    }

    /**
     * 新增数据
     */
    fun loadMore(list: List<out Any>?) {
        list?.let {
            val size = items.size
            items.addAll(list)
            notifyItemRangeInserted(size, list.size)
        }
    }

    /**
     * 新增数据
     */
    fun addItem(item: Any?) {
        item?.let {
            items.add(item)
            notifyItemInserted(items.size - 1)
        }
    }

    /**
     * 删除数据
     */
    fun removeItem(position: Int) {
        if (items.size > position) {
            items.removeAt(position)
            notifyItemRemoved(position)
        }
    }

    override fun getItemCount(): Int = items.size

    /**
     * 获取列表数据
     */
    fun getItem(position: Int) = if (items.size > position) items[position] else null

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): BaseViewHolder<*, out ViewDataBinding> {
        val inflate = inflater.inflate(layoutId, parent, false)
        val holder = viewHolderClass.getConstructor(View::class.java).newInstance(inflate)
        holder.initOnCreate()
        holder.clickListener = this
        return holder
    }

    override fun onBindViewHolder(holder: BaseViewHolder<*, out ViewDataBinding>, position: Int) {
        holder.onBind(getItem(position), position)
    }

    /**
     * 添加点击事件监听
     */
    fun addOnItemClickListener(listener: IOnItemClickListener) {
        _itemClickListenerList.add(listener)
    }

    /**
     * 移除点击事件监听
     */
    fun removeOnItemClickListener(listener: IOnItemClickListener) {
        _itemClickListenerList.remove(listener)
    }

    /**
     * 条目点击事件触发
     */
    override fun onItemClick(position: Int, type: Int) {
        _itemClickListenerList.forEach { it.onItemClick(position, type) }
    }
}