package com.gh.gamecenter.gamedetail.desc

import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gh.common.filter.RegionSettingHelper
import com.gh.common.util.DirectUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.databinding.GamedetailItemGameCollectionBinding
import com.gh.gamecenter.entity.GameDetailRecommendGameEntity

class GameCollectionAdapter(
    private val mRecommendGameList: ArrayList<GameDetailRecommendGameEntity>,
    private val mEntrance: String,
    private val mPath: String
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private val mDefaultHorizontalPadding by lazy { R.dimen.game_detail_item_horizontal_padding.toPx() }

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

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val params = holder.itemView.layoutParams as RecyclerView.LayoutParams
        params.leftMargin = if (position == 0) mDefaultHorizontalPadding else 8F.dip2px()
        params.rightMargin = if (position == itemCount - 1) mDefaultHorizontalPadding else 0F.dip2px()
        holder.itemView.layoutParams = params
        if (holder is GameCollectionItemViewHolder) {
            val entity = mRecommendGameList[position]
            holder.binding.run {
                root.background = R.drawable.background_shape_white_radius_5.toDrawable(root.context)
                titleTv.setTextColor(R.color.text_title.toColor(root.context))
                titleTv.text = entity.title
                ImageUtils.display(coverImage, entity.cover)
                val gameIcons = arrayListOf(gameImage1, gameImage2, gameImage3)
                val games = RegionSettingHelper.filterSimpleGame(entity.games)
                gameIcons.forEachIndexed { index, gameIcon ->
                    gameIcon.goneIf(games.size < index + 1) {
                        gameIcon.displayGameIcon(games[index].toGameEntity())
                        gameIcon.setBorderColor(R.color.background_white)
                    }
                }
                gameCountTv.text = "+${entity.count.game - games.size}"
                root.setOnClickListener {
                    DirectUtils.directToGameCollectionDetail(it.context, entity.id, mEntrance, mPath)
                }
            }
        }
    }

    override fun getItemCount(): Int = mRecommendGameList.size

    class GameCollectionItemViewHolder(val binding: GamedetailItemGameCollectionBinding) :
        RecyclerView.ViewHolder(binding.root)
}