package com.gh.gamecenter.home.horizontalslidevideo

import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.base.BaseRecyclerViewHolder
import com.gh.gamecenter.common.exposure.ExposureSource
import com.gh.gamecenter.common.utils.LeftPagerSnapHelper
import com.gh.gamecenter.common.view.FixLinearLayoutManager
import com.gh.gamecenter.databinding.HomeHorizontalSlideVideoListBinding
import com.gh.gamecenter.entity.SubjectEntity
import com.gh.gamecenter.feature.exposure.ExposureEvent
import com.gh.gamecenter.home.video.ScrollCalculatorHelper

/**
 * 游戏专题-视频横屏滑动
 */
class HomeHorizontalSlideVideoListViewHolder(val binding: HomeHorizontalSlideVideoListBinding) :
    BaseRecyclerViewHolder<Any>(binding.root) {

    fun bindView(
        subject: SubjectEntity,
        entrance: String,
        basicExposureSource: List<ExposureSource>,
        scrollCalculatorHelper: ScrollCalculatorHelper? = null,
        exposureClosure: (ExposureEvent) -> Unit
    ) {
        val context = binding.recyclerView.context
        var adapter = binding.recyclerView.adapter
        val games = subject.data ?: return
        if (adapter is HomeHorizontalSlideVideoAdapter) {
            adapter.checkResetData(games)
            return
        }
        adapter = HomeHorizontalSlideVideoAdapter(context, games, subject.name ?: "", entrance, basicExposureSource) {
            exposureClosure.invoke(it)
        }

        binding.recyclerView.layoutManager =
            FixLinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
        binding.recyclerView.adapter = adapter
        (binding.recyclerView.itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false
        val snapHelper = LeftPagerSnapHelper()
        snapHelper.attachToRecyclerView(binding.recyclerView)
        binding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                scrollCalculatorHelper?.onScroll()
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                scrollCalculatorHelper?.onScrollStateChanged(newState)
            }
        })
    }
}