package com.gh.gamecenter.home.amway;

import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

public class LeftPagerSnapHelper extends PagerSnapHelper {

    @Nullable
    private OrientationHelper mVerticalHelper;

    @Nullable
    private OrientationHelper mHorizontalHelper;

    private int mDecoratedLeft = 0;

    public LeftPagerSnapHelper() {

    }

    public LeftPagerSnapHelper(int mDecoratedLeft) {
        this.mDecoratedLeft = mDecoratedLeft;
    }

    @Nullable
    @Override
    public int[] calculateDistanceToFinalSnap(@NonNull RecyclerView.LayoutManager layoutManager, @NonNull View targetView) {
        int[] out = new int[2];
        if (layoutManager.canScrollHorizontally()) {
            out[0] = distanceToLeft(targetView, getHorizontalHelper(layoutManager));
        }

        // 纵向未经过测试，需要用到的请自行处理
        if (layoutManager.canScrollVertically()) {
            out[1] = distanceToLeft(targetView, getVerticalHelper(layoutManager));
        }
        return out;
    }

    private int distanceToLeft(@NonNull View targetView, OrientationHelper helper) {
        return helper.getDecoratedStart(targetView) - mDecoratedLeft;
    }

    @NonNull
    private OrientationHelper getVerticalHelper(@NonNull RecyclerView.LayoutManager layoutManager) {
        if (mVerticalHelper == null) {
            mVerticalHelper = OrientationHelper.createVerticalHelper(layoutManager);
        }
        return mVerticalHelper;
    }

    @NonNull
    private OrientationHelper getHorizontalHelper(
            @NonNull RecyclerView.LayoutManager layoutManager) {
        if (mHorizontalHelper == null) {
            mHorizontalHelper = OrientationHelper.createHorizontalHelper(layoutManager);
        }
        return mHorizontalHelper;
    }
}
