package com.divya.hardinfo.ui

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.divya.hardinfo.database.SearchHistoryItem
import com.divya.hardinfo.databinding.ItemHistoryBinding

class HistoryAdapter(private val onItemClick: (String) -> Unit) :
    ListAdapter<SearchHistoryItem, HistoryAdapter.HistoryViewHolder>(HistoryDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HistoryViewHolder {
        val binding = ItemHistoryBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return HistoryViewHolder(binding)
    }

    override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class HistoryViewHolder(private val binding: ItemHistoryBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(item: SearchHistoryItem) {
            binding.textQuery.text = item.query
            binding.root.setOnClickListener { onItemClick(item.query) }
        }
    }

    class HistoryDiffCallback : DiffUtil.ItemCallback<SearchHistoryItem>() {
        override fun areItemsTheSame(oldItem: SearchHistoryItem, newItem: SearchHistoryItem): Boolean {
            return oldItem.query == newItem.query
        }

        override fun areContentsTheSame(oldItem: SearchHistoryItem, newItem: SearchHistoryItem): Boolean {
            return oldItem == newItem
        }
    }
}
