package ocelot.desktop.util

import ocelot.desktop.util.FuncUtils.composeN

object SizeFormatting {
  private val Units = Array(
    0 -> "B",
    4 * 1024 -> "kiB",
    1024 * 1024 -> "MiB",
  )

  def formatSize(sizeBytes: Long): String = {
    val power = Units.lastIndexWhere { case (threshold, _) => threshold <= math.abs(sizeBytes) } max 0
    val unitDivisor = composeN(power)((x: Double) => x * 1024)(1)
    val formattedSize =
      if (unitDivisor == 1) sizeBytes.toString
      else f"${sizeBytes / unitDivisor}%.1f"

    s"$formattedSize ${Units(power)._2}"
  }
}
