package com.study.sketch.learning.item;


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

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

import com.study.sketch.learning.SketchingApp;

/**
 * 通用 RecyclerView 间距设置：支持线性 & 网格布局
 */
public class SpacingItemDecoration extends RecyclerView.ItemDecoration {

    private final int spacing;
    private final boolean includeEdge;

    public SpacingItemDecoration(int spacing, boolean includeEdge) {
        this.spacing = dpToPx(spacing);
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect,
                               @NonNull View view,
                               @NonNull RecyclerView parent,
                               @NonNull RecyclerView.State state) {

        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();

        if (layoutManager instanceof GridLayoutManager) {
            GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager;
            int spanCount = gridLayoutManager.getSpanCount();
            int position = parent.getChildAdapterPosition(view); // item 索引
            int column = position % spanCount;

            if (includeEdge) {
                outRect.left = spacing - column * spacing / spanCount;
                outRect.right = (column + 1) * spacing / spanCount;

                if (position < spanCount) {
                    outRect.top = spacing; // 第一行
                }
                outRect.bottom = spacing;
            } else {
                outRect.left = column * spacing / spanCount;
                outRect.right = spacing - (column + 1) * spacing / spanCount;

                if (position >= spanCount) {
                    outRect.top = spacing;
                }
            }
        } else {
            // 默认线性布局（纵向）
            if (includeEdge) {
                outRect.left = spacing;
                outRect.right = spacing;
                outRect.top = spacing;
                outRect.bottom = spacing;
            } else {
                outRect.left = 0;
                outRect.right = 0;
                outRect.top = spacing;
                outRect.bottom = 0;
            }
        }
    }

    public static int dpToPx(int dp) {
        float density = SketchingApp.app.getResources().getDisplayMetrics().density;
        return Math.round(dp * density);
    }

}

