package com.bokecc.livemodule.view;
 
import android.content.Context;
import android.view.View;

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


public class PagerLayoutManager extends LinearLayoutManager {
    private PagerSnapHelper mPagerSnapHelper;
    private OnViewPagerListener mOnViewPagerListener;

    private boolean scrollEnable = true;
    public PagerLayoutManager(Context context, int orientation) {
        super(context, orientation, false);
        init();
    }
 
    private void init() {
        mPagerSnapHelper = new PagerSnapHelper();
    }
 
    @Override
    public void onAttachedToWindow(RecyclerView view) {
        super.onAttachedToWindow(view);
        mPagerSnapHelper.attachToRecyclerView(view);
        if (mOnViewPagerListener != null) {
            mOnViewPagerListener.onPageSelected(0, true, false);
        }
    }
 
    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        super.onLayoutChildren(recycler, state);
    }
 
    /**
     * 滑动状态的改变
     * 缓慢拖拽-> SCROLL_STATE_DRAGGING
     * 快速滚动-> SCROLL_STATE_SETTLING
     * 空闲状态-> SCROLL_STATE_IDLE
     *
     * @param state
     */
    @Override
    public void onScrollStateChanged(int state) {
        switch (state) {
            case RecyclerView.SCROLL_STATE_IDLE:
                View viewIdle = mPagerSnapHelper.findSnapView(this);
                if (viewIdle != null) {
                    int positionIdle = getPosition(viewIdle);
                    if (mOnViewPagerListener != null) {
                        mOnViewPagerListener.onPageSelected(positionIdle, positionIdle == 0,
                                positionIdle == getItemCount() - 1);
                    }
                }
            case RecyclerView.SCROLL_STATE_DRAGGING:
            case RecyclerView.SCROLL_STATE_SETTLING:
                break;
        }
    }
 
    /**
     * 设置监听
     *
     * @param listener
     */
    public void setOnViewPagerListener(OnViewPagerListener listener) {
        this.mOnViewPagerListener = listener;
    }
 
    public interface OnViewPagerListener{
        void onPageSelected(int position, boolean isTop , boolean isBottom);
    }

    public void setScrollEnable(boolean scrollEnable){
        this.scrollEnable = scrollEnable;
    }

    @Override
    public boolean canScrollVertically() {
        return scrollEnable&&super.canScrollVertically();
    }

    @Override
    public boolean canScrollHorizontally() {
        return scrollEnable&&super.canScrollHorizontally();
    }
}