package com.gh.gamecenter.category2

import android.annotation.SuppressLint
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.databinding.RecyclerSearchCategoryResultBinding

class SearchCategoryResultsAdapter(val clickListener: (CategoryV2ViewModel.SelectedTags) -> Unit) :
    RecyclerView.Adapter<SearchCategoryResultsAdapter.ResultViewHolder>() {
    private val dataList = arrayListOf<CategoryV2ViewModel.SelectedTags>()
    private var key = ""

    @SuppressLint("NotifyDataSetChanged")
    fun setData(data: List<CategoryV2ViewModel.SelectedTags>, newKey: String) {
        key = newKey
        dataList.clear()
        dataList.addAll(data)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ResultViewHolder {
        return ResultViewHolder(parent.toBinding())
    }

    override fun getItemCount() = dataList.size

    override fun onBindViewHolder(holder: ResultViewHolder, position: Int) {
        val item = dataList[position]
        val text = item.category.name ?: ""
        val spannableString = SpannableString(text)
        val highlightColor = com.gh.gamecenter.common.R.color.text_theme.toColor(holder.itemView.context)
        text.forEachIndexed { index, char ->
            if (key.contains(char)) {
                // 需要高亮
                spannableString.setSpan(
                    ForegroundColorSpan(highlightColor),
                    index,
                    index + 1,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
        }
        holder.binding.root.text = spannableString
        holder.itemView.setOnClickListener {
            clickListener(item)
        }
    }

    class ResultViewHolder(val binding: RecyclerSearchCategoryResultBinding) : RecyclerView.ViewHolder(binding.root) {

    }
}