package com.gh.gamecenter.catalog

import android.content.Context
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.R
import com.gh.gamecenter.databinding.CatalogItemBinding
import com.gh.gamecenter.entity.CatalogEntity
import com.lightgame.adapter.BaseRecyclerAdapter

class CatalogAdapter(
    context: Context,
    private val mFragment: CatalogFragment,
    private val mViewModel: CatalogViewModel,
    private val mList: List<CatalogEntity.SubCatalogEntity>
) : BaseRecyclerAdapter<CatalogAdapter.CatalogItemViewHolder>(context) {

    override fun getItemCount() = mList.size

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

    override fun onBindViewHolder(holder: CatalogItemViewHolder, position: Int) {
        holder.binding.run {
            val catalogEntity = mList[position]
            catalogName.text = catalogEntity.name
            recommendTag.goneIf(!catalogEntity.recommended)
            if (catalogEntity.name == mViewModel.selectedCatalogName) {
                selectedTag.visibility = View.VISIBLE
                catalogName.setTextColor(R.color.theme_font.toColor(mContext))
                root.setBackgroundColor(R.color.background_white.toColor(mContext))
            } else {
                selectedTag.visibility = View.GONE
                catalogName.setTextColor(R.color.text_title.toColor(mContext))
                root.background = null
            }
            root.setOnClickListener {
                if (catalogEntity.name != mViewModel.selectedCatalogName) {
                    mViewModel.selectedCatalogName = catalogEntity.name
                    mViewModel.logSubCatalogClick(position)
                    mFragment.changeCatalog(position)
                    notifyDataSetChanged()
                }
            }
        }
    }

    class CatalogItemViewHolder(val binding: CatalogItemBinding) : BaseRecyclerViewHolder<Any>(binding.root)
}