package com.remax.visualnovel.widget.itemdecoration

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

//定义2个Item之间的距离
class HorizontalItemDecoration(private val space: Int, private val startSpace: Int = 0, private val endSpace: Int = 0) : ItemDecoration() {
    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        val position = parent.getChildAdapterPosition(view)
        val totalCount = parent.adapter!!.itemCount
        if ((parent.layoutManager as LinearLayoutManager).reverseLayout) {
            when (position) {
                0 -> { //第一个
                    outRect.right = startSpace
                    outRect.left = space / 2
                }

                totalCount - 1 -> { //最后一个
                    outRect.right = space / 2
                    outRect.left = endSpace
                }

                else -> { //中间其它的
                    outRect.left = space / 2
                    outRect.right = space / 2
                }
            }
            if (totalCount == 1) {
                outRect.left = endSpace
            }
        } else {
            when (position) {
                0 -> { //第一个
                    outRect.left = startSpace
                    outRect.right = space / 2
                }

                totalCount - 1 -> { //最后一个
                    outRect.left = space / 2
                    outRect.right = endSpace
                }

                else -> { //中间其它的
                    outRect.left = space / 2
                    outRect.right = space / 2
                }
            }
            if (totalCount == 1) {
                outRect.right = endSpace
            }
        }
    }
}