package com.adealink.weparty.commonui.recycleview.itemdecoration

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

class GridSpacingItemDecoration(
    var spanCount: Int,
    var spacingH: Int,
    private val spacingV: Int,
    private val includeEdge: Boolean,
    private val extraBottom: Int = -1,
    private val extraTop: Int = -1
) :
    RecyclerView.ItemDecoration() {

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        val totalCount = state.itemCount
        val position = parent.getChildAdapterPosition(view) // item position
        val column = position % spanCount // item column
        val isRtl = parent.layoutDirection == View.LAYOUT_DIRECTION_RTL
        if (includeEdge) {
            val left =
                spacingH - column * spacingH / spanCount // spacing - column * ((1f / spanCount) * spacing)
            val right =
                (column + 1) * spacingH / spanCount // (column + 1) * ((1f / spanCount) * spacing)
            outRect.left = if (isRtl) right else left
            outRect.right = if (isRtl) left else right

            if (position < spanCount) { // top edge
                outRect.top = spacingV
            }
            outRect.bottom = spacingV // item bottom
        } else {
            val left = column * spacingH / spanCount // column * ((1f / spanCount) * spacing)
            val right =
                spacingH - (column + 1) * spacingH / spanCount // spacing - (column + 1) * ((1f /    spanCount) * spacing)
            outRect.left = if (isRtl) right else left
            outRect.right = if (isRtl) left else right
            if (position >= spanCount) {
                outRect.top = spacingV // item top
            }
        }

        if (extraBottom != -1) {
            val temp = totalCount % spanCount
            val lastRowCount = if (temp == 0) spanCount else temp
            val isLastRow = totalCount - 1 - position < lastRowCount
            if (isLastRow) {
                outRect.bottom += extraBottom
            }
        }

        if (extraTop != -1) {
            val isFirstRow = position < spanCount
            if (isFirstRow) {
                outRect.top += extraTop
            }
        }
    }
}