package com.gh.gamecenter.category2

import android.content.Context
import android.graphics.Typeface
import android.view.View
import android.view.ViewGroup
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.toBinding
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.databinding.CategoryV2ItemBinding
import com.gh.gamecenter.entity.SidebarsEntity
import com.lightgame.adapter.BaseRecyclerAdapter

class CategoryV2Adapter(
    context: Context,
    private val mViewModel: CategoryV2ViewModel,
    private val mList: List<SidebarsEntity.SidebarEntity>
) : BaseRecyclerAdapter<CategoryV2Adapter.CategoryV2ItemViewHolder>(context) {

    var selectedPosition = 0
        private set

    override fun getItemCount() = mList.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        CategoryV2ItemViewHolder(parent.toBinding())

    override fun onBindViewHolder(holder: CategoryV2ItemViewHolder, position: Int) {
        holder.binding.run {
            val catalogEntity = mList[position]
            catalogName.text = catalogEntity.name
            recommendTag.goneIf(!catalogEntity.recommended)
            if (position == selectedPosition) {
                selectedTag.visibility = View.VISIBLE
                catalogName.setTextColor(com.gh.gamecenter.common.R.color.text_primary.toColor(mContext))
                catalogName.setTypeface(null, Typeface.BOLD)
                root.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_surface.toColor(mContext))
            } else {
                selectedTag.visibility = View.GONE
                catalogName.setTextColor(com.gh.gamecenter.common.R.color.text_tertiary.toColor(mContext))
                catalogName.setTypeface(null, Typeface.NORMAL)
                root.setBackgroundColor(com.gh.gamecenter.common.R.color.ui_background.toColor(mContext))
            }
            root.setOnClickListener {
                if (position != selectedPosition) {
                    mViewModel.logClickSide()
                    mViewModel.selectSidebarsPosition(position)
                }
            }
        }
    }

    fun selectPosition(newPosition: Int) {
        if (selectedPosition == newPosition) {
            return
        }
        val oldSelection = selectedPosition
        selectedPosition = newPosition
        notifyItemChanged(oldSelection)
        notifyItemChanged(newPosition)
    }

    class CategoryV2ItemViewHolder(val binding: CategoryV2ItemBinding) : BaseRecyclerViewHolder<Any>(binding.root)
}