package com.gh.gamecenter.qa.article.detail

import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil.ItemCallback
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView.NO_POSITION
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.gh.gamecenter.common.utils.layoutInflater
import com.gh.gamecenter.databinding.ItemTopCommunityCategoryBinding
import com.gh.gamecenter.qa.entity.TopCommunityCategory

class TopCommunityCategoryAdapter(
    private val callback: (TopCommunityCategory) -> Unit
) : ListAdapter<TopCommunityCategory, TopCommunityCategoryAdapter.ArticleDetailTopCategoryViewHolder>(COMPARATOR) {

    private var selectedPosition = -1

    companion object {
        private val COMPARATOR = object: ItemCallback<TopCommunityCategory>() {
            override fun areItemsTheSame(
                oldItem: TopCommunityCategory,
                newItem: TopCommunityCategory
            ) : Boolean = oldItem == newItem

            override fun areContentsTheSame(
                oldItem: TopCommunityCategory,
                newItem: TopCommunityCategory
            ) : Boolean = oldItem == newItem
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleDetailTopCategoryViewHolder =
        ArticleDetailTopCategoryViewHolder(
            ItemTopCommunityCategoryBinding.inflate(
                parent.layoutInflater,
                parent,
                false
            )
        )

    override fun onBindViewHolder(holder: ArticleDetailTopCategoryViewHolder, position: Int) {
        val titleView = holder.binding.root

        titleView.text = getItem(position).title
        titleView.isSelected = selectedPosition == position

        titleView.setOnClickListener {
            val pos = holder.bindingAdapterPosition
            if (pos == NO_POSITION) return@setOnClickListener

            it.isSelected = true

            val oldPos = selectedPosition
            selectedPosition = pos
            notifyItemChanged(oldPos)
            callback.invoke(getItem(pos))
        }
    }



    class ArticleDetailTopCategoryViewHolder(
        val binding: ItemTopCommunityCategoryBinding
    ) : ViewHolder(binding.root)
}