package com.gh.gamecenter.subject.tab

import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DiffUtil.ItemCallback
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.debounceActionWithInterval
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.common.view.Chips
import com.gh.gamecenter.databinding.ItemColumnCollectionCustomTabBinding
import com.gh.gamecenter.entity.SubjectData

class CustomTabFollowAdapter(private val viewModel: ColumnCollectionTabViewModel?) :
    ListAdapter<SubjectData, CustomTabFollowAdapter.CustomTabFollowItemViewHolder>(createDiffItemCallBack()) {
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): CustomTabFollowItemViewHolder {
        return CustomTabFollowItemViewHolder(parent.toBinding())
    }

    override fun onBindViewHolder(holder: CustomTabFollowItemViewHolder, position: Int) {
        val subjectData = currentList.getOrNull(position) ?: return
        val isForbidden = subjectData.isForbidden
        holder.binding.chips.run {
            setState(if (isForbidden) Chips.STATE_FILL else Chips.STATE_DEFAULT)
            setText(subjectData.subjectName ?: "")
            endIcon.isVisible = !isForbidden
            endIcon.setImageResource(R.drawable.ic_basic_x_8_secondary)
            endIcon.imageTintList = null
            setOnClickListener {
                debounceActionWithInterval(500) {
                    if (!isForbidden) {
                        viewModel?.addMore(subjectData)
                    }
                }
            }
        }
    }

    class CustomTabFollowItemViewHolder(val binding: ItemColumnCollectionCustomTabBinding) :
        ViewHolder(binding.root)

    companion object {

        fun createDiffItemCallBack() = object : ItemCallback<SubjectData>() {
            override fun areItemsTheSame(oldItem: SubjectData, newItem: SubjectData): Boolean {
                return oldItem == newItem
            }

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

        }
    }
}