package com.gh.gamecenter.video.label

import android.content.Context
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.common.utils.visibleIf
import com.gh.gamecenter.common.utils.setRootBackgroundColor
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.databinding.VideoLabelItemBinding
import com.gh.gamecenter.entity.ActivityLabelEntity
import com.lightgame.adapter.BaseRecyclerAdapter

class VideoLabelAdapter(
    context: Context,
    private val selectTagActivityId: String,
    private val callback: (ActivityLabelEntity?) -> Unit
) : BaseRecyclerAdapter<RecyclerView.ViewHolder>(context) {

    val entityList = ArrayList<ActivityLabelEntity>()
    var selectPosition = -1

    fun setListData(updateData: List<ActivityLabelEntity>) {
        entityList.clear()
        entityList.addAll(updateData)
        selectPosition = entityList.indexOfFirst { it.id == selectTagActivityId }
        notifyDataSetChanged()
    }

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


    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is VideoLabelViewHolder) {
            holder.binding.run {
                root.setRootBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface)
                titleTv.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(mContext))
                contentTv.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(mContext))
            }

            val activityLabelEntity = entityList[position]
            holder.binding.titleTv.text = activityLabelEntity.name
            holder.binding.contentTv.text = activityLabelEntity.desc.ifEmpty { activityLabelEntity.remark }
            holder.binding.selectedIv.visibleIf(selectPosition == position)
            holder.itemView.setOnClickListener {
                val lastPos: Int
                if (selectPosition != position) {
                    lastPos = selectPosition
                    selectPosition = position
                    callback.invoke(activityLabelEntity)
                } else {
                    lastPos = selectPosition
                    selectPosition = -1
                    callback.invoke(null)
                }
                notifyItemChanged(lastPos)
                notifyItemChanged(selectPosition)
            }
        }
    }

    override fun getItemCount(): Int = entityList.size

    fun getSelectedActivity(): ActivityLabelEntity? {
        if (selectPosition >= 0) {
            return entityList[selectPosition]
        }
        return null
    }

    class VideoLabelViewHolder(val binding: VideoLabelItemBinding) : BaseRecyclerViewHolder<Any>(binding.root)
}