package com.gh.gamecenter.common.view.vertical_recycler

import android.content.Context
import android.graphics.PointF
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.common.utils.tryWithDefaultCatch

class SnappingLinearLayoutManager(val context: Context) : LinearLayoutManager(context) {
    override fun smoothScrollToPosition(recyclerView: RecyclerView?, state: RecyclerView.State?, position: Int) {
        tryWithDefaultCatch {
            val smoothScroller = object : LinearSmoothScroller(context) {
                override fun getVerticalSnapPreference(): Int = SNAP_TO_START
                override fun computeScrollVectorForPosition(targetPosition: Int): PointF =
                    this@SnappingLinearLayoutManager.computeScrollVectorForPosition(targetPosition)
                        ?: PointF(0F, 0F)
            }
            smoothScroller.targetPosition = position
            startSmoothScroll(smoothScroller)
        }
    }

    override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
        tryWithDefaultCatch { super.onLayoutChildren(recycler, state) }
    }
}