package com.drawing.drawsketch

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import androidx.recyclerview.widget.StaggeredGridLayoutManager



class ItemSpace(v: Int, h: Int, ex: Int) : ItemDecoration() {
    private val v: Int
    private val h: Int
    private val ex: Int

    init {
        this.v = Math.round(dpToPx(v.toFloat()))
        this.h = Math.round(dpToPx(h.toFloat()))
        this.ex = Math.round(dpToPx(ex.toFloat()))
    }

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        var spanCount = 1
        var spanSize = 1
        var spanIndex = 0

        val childAdapterPosition = parent.getChildAdapterPosition(view)
        val layoutManager = parent.layoutManager
        if (layoutManager is StaggeredGridLayoutManager) {
            val layoutParams = view.layoutParams as StaggeredGridLayoutManager.LayoutParams
            spanCount = layoutManager.spanCount
            if (layoutParams.isFullSpan) {
                spanSize = spanCount
            }
            spanIndex = layoutParams.spanIndex
        } else if (layoutManager is GridLayoutManager) {
            val gridLayoutManager = layoutManager
            val layoutParams = view.layoutParams as GridLayoutManager.LayoutParams
            spanCount = gridLayoutManager.spanCount
            spanSize = gridLayoutManager.spanSizeLookup.getSpanSize(childAdapterPosition)
            spanIndex = layoutParams.spanIndex
        } else if (layoutManager is LinearLayoutManager) {
            outRect.left = v
            outRect.right = v
            outRect.bottom = h
        }

        if (spanSize == spanCount) {
            outRect.left = v + ex
            outRect.right = v + ex
            outRect.bottom = h
        } else {
            val itemAllSpacing = (v * (spanCount + 1) + ex * 2) / spanCount
            val left = v * (spanIndex + 1) - itemAllSpacing * spanIndex + ex
            val right = itemAllSpacing - left
            outRect.left = left
            outRect.right = right
            outRect.bottom = h
        }
    }


    companion object {
        fun dpToPx(dpValue: Float): Float {
            val density: Float = App.mInstance.resources.displayMetrics.density
            return density * dpValue + 0.5f
        }
    }
}