package com.datarecovery.master.utils;

import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class GridLayoutItemDecoration extends RecyclerView.ItemDecoration {

    private int spanCount;
    private float horizontalGapPercent;
    private float verticalGapPercent;

    private boolean showLastVertical;

    public GridLayoutItemDecoration() {

    }


    public GridLayoutItemDecoration(int spanCount, float horizontalGapPercent, float verticalGapPercent) {
        this.spanCount = spanCount;
        this.horizontalGapPercent = horizontalGapPercent;
        this.verticalGapPercent = verticalGapPercent;
    }

    public void setParam(int spanCount, float horizontalGapPercent, float verticalGapPercent) {
        this.spanCount = spanCount;
        this.horizontalGapPercent = horizontalGapPercent;
        this.verticalGapPercent = verticalGapPercent;
    }

    public void setShowLastVertical(boolean showLastVertical) {
        this.showLastVertical = showLastVertical;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int horizontalGap = (int) (parent.getMeasuredWidth() * horizontalGapPercent);
        int verticalGap = (int) (parent.getMeasuredWidth() * verticalGapPercent);
        int singleGap = horizontalGap * (spanCount - 1) / spanCount;
        int childAdapterPosition = parent.getChildAdapterPosition(view);
        int i = childAdapterPosition % spanCount;
        outRect.top = 0;
        if (!showLastVertical && parent.getAdapter() != null && parent.getAdapter().getItemCount() - spanCount <= childAdapterPosition) {
            outRect.bottom = 0;
        } else {
            outRect.bottom = verticalGap;
        }
        outRect.left = 0;
        outRect.right = 0;
        if (i == 0) {
            outRect.right = singleGap;
        } else if (i == spanCount - 1) {
            outRect.left = singleGap;
        } else {
            outRect.left = singleGap / 2;
            outRect.right = singleGap / 2;
        }
    }
}