package com.develop.food.base.widgets

import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class LinearPositionObserver(
    private val onPositionChange: (position: Int) -> Unit
): RecyclerView.OnScrollListener() {

    private var lastReportPosition: Int = -1

    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
        super.onScrollStateChanged(recyclerView, newState)
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            val layoutManager = recyclerView.layoutManager as LinearLayoutManager
            val position = layoutManager.findFirstVisibleItemPosition()
            if (position < 0) {
                return
            }
            if (lastReportPosition == position) {
                return
            }
            lastReportPosition = position
            onPositionChange(position)
        }
    }
}