package com.datarecovery.master.utils;

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

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

public class GridRecoverItemDecoration extends RecyclerView.ItemDecoration {

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

    private boolean showLastVertical = true;

    public GridRecoverItemDecoration(int spanCount, float horizontalGapPercent, float verticalGapPercent) {
        this(spanCount, horizontalGapPercent, verticalGapPercent, true);
    }

    public GridRecoverItemDecoration(int spanCount, float horizontalGapPercent, float verticalGapPercent, boolean showLastVertical) {
        this.spanCount = spanCount;
        this.horizontalGapPercent = horizontalGapPercent;
        this.verticalGapPercent = verticalGapPercent;
        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 spanSize = ((GridLayoutManager.LayoutParams) view.getLayoutParams()).getSpanSize();
        int singleGap = horizontalGap * (spanCount - 1) / spanCount;
        int childAdapterPosition = parent.getChildAdapterPosition(view);
        int i = childAdapterPosition % spanSize;
        outRect.top = 0;
        if (spanSize == 1) {
            if (!showLastVertical && parent.getAdapter() != null && parent.getAdapter().getItemCount() - spanSize <= 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;
            }
        } else {
            outRect.left = 0;
            outRect.right = 0;
            outRect.bottom = 0;
        }
    }
}