package com.rdiot.yx485.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.rdiot.yx485.R
import com.rdiot.yx485.bean.FamilyData
import com.rdiot.yx485.bean.RoomData
import com.rdiot.yx485.databinding.ItemFamilyBinding
import com.rdiot.yx485.util.setClickLimitListener

/**
 * 家庭适配器
 * @author mR2hao
 * @date 2022/12/3
 */
class FamilyAdapter(
    private val mListener: OnItemClickListener? = null
) : RecyclerView.Adapter<FamilyAdapter.BaseViewHolder>() {
    inner class BaseViewHolder(val dataBinding: ItemFamilyBinding) :
        RecyclerView.ViewHolder(dataBinding.root)

    private var mList: MutableList<FamilyData> = mutableListOf()

    interface OnItemClickListener {
        fun onItemClicked(position: Int, familyData: FamilyData)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
        val binding: ItemFamilyBinding = DataBindingUtil.inflate(
            LayoutInflater.from(parent.context),
            R.layout.item_family,
            parent,
            false
        )

        return BaseViewHolder(binding)
    }

    override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
        val bean = mList[position]
        holder.dataBinding.familyData = bean

        holder.dataBinding.clItem.setClickLimitListener {
            mListener?.onItemClicked(position, bean)
        }
    }

    @Synchronized
    fun update(list: List<FamilyData>) {
        if (list.size < this.mList.size) {
            mList.clear()
            mList.addAll(list)
            notifyDataSetChanged()
        } else {
            for (i in list.indices) {
                if (i < this.mList.size) {
                    if (this.mList[i] != list[i]) {
                        this.mList[i] = list[i]
                        notifyItemChanged(i)
                    }
                } else {
                    this.mList.add(list[i])
                    notifyItemInserted(i)
                }
            }
        }
    }

    override fun getItemCount() = mList.size
}