package fr.iut.ouafff.ui.utils

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import fr.iut.ouafff.data.Dog
import fr.iut.ouafff.databinding.ItemListDogBinding

class DogRecyclerViewAdapter(private val listener: Callbacks) :
    ListAdapter<Dog, DogRecyclerViewAdapter.DogViewHolder>(DiffUtilDogCallback) {

    private object DiffUtilDogCallback : DiffUtil.ItemCallback<Dog>() {
        override fun areItemsTheSame(oldItem: Dog, newItem: Dog) = oldItem.id == newItem.id
        override fun areContentsTheSame(oldItem: Dog, newItem: Dog) = oldItem == newItem
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        DogViewHolder(
            ItemListDogBinding.inflate(LayoutInflater.from(parent.context)), listener
        )


    override fun onBindViewHolder(holder: DogViewHolder, position: Int) =
        holder.bind(getItem(position))


    class DogViewHolder(private val binding: ItemListDogBinding, listener: Callbacks) :
        RecyclerView.ViewHolder(binding.root) {

        val dog: Dog? get() = binding.dog

        init {
            itemView.setOnClickListener { dog?.let { listener.onDogSelected(it.id) } }
        }

        fun bind(dog: Dog) {
            binding.dog = dog
            binding.executePendingBindings()
        }

    }

    interface Callbacks {
        fun onDogSelected(dogId: Long)
    }
}
