package com.gh.gamecenter.game.vertical

import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.databinding.GameVerticalSlideItemBinding
import com.gh.gamecenter.entity.SubjectEntity
import com.gh.gamecenter.feature.entity.GameEntity
import kotlin.math.min

/**
 * 游戏专题-竖屏滑动
 */
class GameVerticalSlideViewHolder(val binding: GameVerticalSlideItemBinding) :
    BaseRecyclerViewHolder<Any>(binding.root) {

    fun bindVerticalSlide(
        verticalSlide: SubjectEntity,
        itemClick: (Int, GameEntity) -> Unit,
        transparentBackground: Boolean = false,
    ): SpanCountPagerSnapHelper {
        val context = binding.root.context
        val spanCount = min(verticalSlide.list, verticalSlide.data!!.size)
        val snapHelper = SpanCountPagerSnapHelper(spanCount, true)
        binding.recyclerView.run {
            clearOnScrollListeners()
            (itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
            onFlingListener = null

            if (layoutManager !is GridLayoutManager || (layoutManager as GridLayoutManager).spanCount != spanCount) {
                layoutManager = GridLayoutManager(context, spanCount, RecyclerView.HORIZONTAL, false)
            }

            if (adapter is GameVerticalAdapter) {
                val verticalAdapter = adapter as GameVerticalAdapter
                verticalAdapter.checkResetData(verticalSlide)
            } else {
                adapter = GameVerticalAdapter(context, verticalSlide, itemClick, transparentBackground)
            }
            snapHelper.attachToRecyclerView(this)
            isNestedScrollingEnabled = false
        }

        return snapHelper
    }
}
