package com.keyborad.theme.trendyborad.trendyutils;

import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

public class TrendyInfinitePagerSnapHelper extends PagerSnapHelper {

    private OnPageChangedListener onPageChangedListener;

    public interface OnPageChangedListener {
        void onPageChanged(int position);
    }

    public void setOnPageChangedListener(OnPageChangedListener listener) {
        this.onPageChangedListener = listener;
    }

    @Override
    public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY) {
        int targetPosition = super.findTargetSnapPosition(layoutManager, velocityX, velocityY);

        if (layoutManager instanceof LinearLayoutManager && onPageChangedListener != null) {
            onPageChangedListener.onPageChanged(targetPosition);
        }

        return targetPosition;
    }

    @Override
    public View findSnapView(RecyclerView.LayoutManager layoutManager) {
        View snapView = super.findSnapView(layoutManager);

        // 确保找到的View不为空
        if (snapView == null && layoutManager instanceof LinearLayoutManager) {
            LinearLayoutManager lm = (LinearLayoutManager) layoutManager;
            int firstVisible = lm.findFirstVisibleItemPosition();
            if (firstVisible != RecyclerView.NO_POSITION) {
                snapView = lm.findViewByPosition(firstVisible);
            }
        }

        return snapView;
    }
}