/*
 * Copyright (C) 2026 SHX VPN
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 */

package org.strongswan.android.ui.compose

import java.util.Locale
import kotlin.math.abs

fun formatBytes(bytes: Long): String
{
	if (bytes <= 0L)
	{
		return "0 B"
	}
	val units = arrayOf("B", "KB", "MB", "GB", "TB")
	var value = bytes.toDouble()
	var unit = 0
	while (value >= 1024 && unit < units.lastIndex)
	{
		value /= 1024
		unit++
	}
	return if (unit == 0) String.format(Locale.US, "%d %s", bytes, units[unit])
	else String.format(Locale.US, "%.1f %s", value, units[unit])
}

fun formatRate(bytesPerSecond: Long): String
{
	if (abs(bytesPerSecond) < 32)
	{
		return "0 B/s"
	}
	return formatBytes(bytesPerSecond) + "/s"
}

fun formatDuration(seconds: Long): String
{
	val s = seconds.coerceAtLeast(0)
	val h = s / 3600
	val m = (s % 3600) / 60
	val sec = s % 60
	return if (h > 0) String.format(Locale.US, "%d:%02d:%02d", h, m, sec)
	else String.format(Locale.US, "%02d:%02d", m, sec)
}
