package com.remax.visualnovel.widget.itemdecoration

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

/**
 * Created by HJW on 2020/11/19
 * @params 横条目数量,行间距,列间距
 */
class HorizontalGridSpaceItemDecoration(
    private val spanCount: Int,
    private val space: Int, //左右间距
    private val startSpace: Int = 0,
    private val endSpace: Int = 0,
    private val headerCount: Int = 0
) : RecyclerView.ItemDecoration() {

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        val position = parent.getChildAdapterPosition(view) // 获取view 在adapter中的位置。

        if (position < headerCount) {
            return
        }

        val totalCount = parent.adapter!!.itemCount
        var totalRow = totalCount / spanCount // 总行数
        val d = totalCount % spanCount
        if (d > 0) {
            totalRow++
        }
        var row = (position + 1) / spanCount // view 所在的行
        val p = (position + 1) % spanCount
        if (p > 0) {
            row++
        }

        outRect.left = if (position < spanCount) startSpace else space / 2
        outRect.right = if (row == totalRow) endSpace else space / 2

    }
}