package com.gh.gamecenter.search

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.common.utils.toDrawable
import com.gh.gamecenter.databinding.ItemSearchResultCardBinding
import com.gh.gamecenter.feature.entity.FirstSetting

class SearchGameFirstCardsAdapter(
    private val cardClick: (Int, FirstSetting.Card.Preview) -> Unit
) :
    RecyclerView.Adapter<SearchGameFirstCardsAdapter.SearchCardsViewHolder>() {

    private val dataList = arrayListOf<FirstSetting.Card.Preview>()

    @SuppressLint("NotifyDataSetChanged")
    fun setData(data: List<FirstSetting.Card.Preview>) {
        dataList.clear()
        dataList.addAll(data)
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int = dataList.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchCardsViewHolder {
        return SearchCardsViewHolder.create(parent)
    }


    override fun onBindViewHolder(holder: SearchCardsViewHolder, position: Int) {
        val item = dataList[position]
        holder.bind(item)
        holder.binding.ivCard.setOnClickListener {
            cardClick(position, item)
        }

    }

    class SearchCardsViewHolder(
        val binding: ItemSearchResultCardBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        fun bind(item: FirstSetting.Card.Preview) {
            binding.tvTitle.text = item.cardName
            ImageUtils.display(binding.ivCard, item.icon)

            // 在代码中设置View的颜色（在xml中定义，切换浅色模式时颜色可能不会变）
            binding.tvTitle.setTextColor(ContextCompat.getColor(itemView.context, com.gh.gamecenter.common.R.color.text_primary))
            binding.vBorder.background = R.drawable.border_search_game_first_card.toDrawable(itemView.context)
        }

        companion object {

            fun create(parent: ViewGroup): SearchCardsViewHolder {
                val inflater = LayoutInflater.from(parent.context)
                val binding = ItemSearchResultCardBinding.inflate(inflater, parent, false)
                return SearchCardsViewHolder(binding)
            }
        }
    }
}