<?php

namespace Internetgalerie\IgDatapoolFe\Utility;

use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;

/**
 * Renders an ajaax uploader
 *
 * @api
 * @author     Markus Baumgartner <mb@stylesheep.ch>, Internetgalerie AG
 * @package    IgDatapoolFE
 * @subpackage ViewHelpers
 */
class BytesUtility
{
    public static function formatBytes($bytes, $decimals = 0, $decimalSeparator = '.', $thousandsSeparator = ',', $units = null)
    {
        if ($units === null) {
            $units = LocalizationUtility::translate('LLL:EXT:fluid/Resources/Private/Language/locallang.xlf:viewhelper.format.bytes.units');
        }
        $units = GeneralUtility::trimExplode(',', $units, true);

        $value = $bytes;

        if (is_numeric($value)) {
            $value = (float)$value;
        }
        if (!is_int($value) && !is_float($value)) {
            $value = 0;
        }
        $bytes = max($value, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);
        $bytes /= 2 ** (10 * $pow);

        return sprintf(
            '%s %s',
            number_format(
                round($bytes, 4 * $decimals),
                $decimals,
                $decimalSeparator,
                $thousandsSeparator
            ),
            $units[$pow]
        );
    }
}
