/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.micode.notes.ui;

import android.graphics.Rect;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

/**
 * 瀑布流布局间距装饰类
 * <p>
 * 为瀑布流布局的RecyclerView添加统一的间距，确保每个网格项之间有合适的间隔。
 * 支持是否包含边缘间距的配置。
 * </p>
 */
public class StaggeredGridSpacingItemDecoration extends RecyclerView.ItemDecoration {
    private int spanCount;
    private int spacing;
    private boolean includeEdge;

    /**
     * 构造函数
     * @param spanCount 网格列数
     * @param spacing 间距大小（像素）
     * @param includeEdge 是否包含边缘间距
     */
    public StaggeredGridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        StaggeredGridLayoutManager.LayoutParams params = 
                (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();
        int spanIndex = params.getSpanIndex();

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

            if (params.getViewAdapterPosition() < spanCount) {
                outRect.top = spacing;
            }
            outRect.bottom = spacing;
        } else {
            outRect.left = spanIndex * spacing / spanCount;
            outRect.right = spacing - (spanIndex + 1) * spacing / spanCount;
            if (params.getViewAdapterPosition() >= spanCount) {
                outRect.top = spacing;
            }
        }
    }
}
