package com.gh.gamecenter.game.vertical

import androidx.recyclerview.widget.RecyclerView


class OnPagerSnapScrollListener(
    private val snapHelper: SpanCountPagerSnapHelper,
    private val onPageChangeListener: (Int) -> Unit
) : RecyclerView.OnScrollListener() {

    private var oldPosition = -1 //防止同一Position多次触发

    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
        super.onScrollStateChanged(recyclerView, newState)
        var position = 0
        val layoutManager = recyclerView.layoutManager
        val view = snapHelper.findSnapView(layoutManager)
        if (view != null && layoutManager != null) {
            position = Math.ceil((layoutManager.getPosition(view) / snapHelper.spanCount).toDouble()).toInt()
        }
        if (newState == RecyclerView.SCROLL_STATE_IDLE && oldPosition != position) {
            oldPosition = position
            onPageChangeListener.invoke(position)
        }
    }
}