package compose.utils

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import kotlin.math.roundToInt


/**
 * Places children such that each child receives the same amount of space and is centered within that space.
 */
@Suppress("UnusedReceiverParameter")
val Arrangement.EqualRoomCentered: Arrangement.HorizontalOrVertical
    get() = EqualRoomCenteredArrangement


private val EqualRoomCenteredArrangement = object : Arrangement.HorizontalOrVertical {

    override val spacing = 0.dp

    override fun Density.arrange(
        totalSize: Int,
        sizes: IntArray,
        layoutDirection: LayoutDirection,
        outPositions: IntArray
    ) = if (layoutDirection == LayoutDirection.Ltr) {
        placeEqually(totalSize, sizes, outPositions, reverseInput = false)
    } else {
        placeEqually(totalSize, sizes, outPositions, reverseInput = true)
    }

    override fun Density.arrange(
        totalSize: Int,
        sizes: IntArray,
        outPositions: IntArray
    ) = placeEqually(totalSize, sizes, outPositions, reverseInput = false)

    override fun toString() = "EqualRoomArrangement"

}


private fun placeEqually(
    totalSize: Int,
    size: IntArray,
    outPosition: IntArray,
    reverseInput: Boolean
) {
    val itemRoom = totalSize.toFloat() / size.size
    var current = 0f
    size.forEachIndexed(reverseInput) { index, it ->
        outPosition[index] = (current + (itemRoom - it)/2).roundToInt()
        current += itemRoom
    }
}


private inline fun IntArray.forEachIndexed(reversed: Boolean, action: (Int, Int) -> Unit) {
    if (!reversed) {
        forEachIndexed(action)
    } else {
        for (i in (size - 1) downTo 0) {
            action(i, get(i))
        }
    }
}
