package com.atmob.keyboard_android.util.recyclerview

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

/**
 * 网格布局分割线
 */
class GridDivider(
    // 列数
    private val spanCount: Int,
    // 分割线宽度，单位为px
    private val spacing: Int
) : RecyclerView.ItemDecoration() {

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        val position = parent.getChildAdapterPosition(view)
        // 当前列索引
        val column = position % spanCount

        // 右边距，非最后一列添加间距
//        outRect.right = if (column < spanCount - 1) {
//            spacing
//        } else {
//            0
//        }

        // 右边距，如果是最后一列，则添加一半的间距
//        outRect.right = if (column < spanCount - 1) {
//            spacing
//        } else {
//            spacing / 2
//        }

        // 右边距，都添加
        outRect.right = spacing

        // 下边距，非最后一行添加间距
//        val totalItemCount = parent.adapter?.itemCount ?: 0
//        val row = position / spanCount
//        val totalRows = (totalItemCount + spanCount - 1) / spanCount
//        outRect.bottom = if (row < totalRows - 1) {
//            spacing
//        } else {
//            0
//        }

        // 都添加下边距
        outRect.bottom = spacing
    }
}