<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Helper;

/**
 * Class Profiler
 */
class Profiler
{
    /**
     * @var int
     */
    protected static $level = 0;

    /**
     * @var bool
     */
    protected static $firstTime = true;

    /**
     * @param $section
     */
    public static function start($section)
    {
        if(getenv('REFILO_PROFILER') !== 'true') {
            return;
        }

        if(self::$firstTime) {
            echo PHP_EOL, PHP_EOL;
            self::$firstTime = false;
        }

        echo str_repeat('-', 1 + self::$level * 2), ' ', $section, ' : ';
        self::memoryUsage();
        self::$level++;
    }

    /**
     *
     */
    public static function memoryUsage()
    {
        $usage = memory_get_usage(true);

        if ($usage < 1024) {
            echo "$usage bytes", PHP_EOL;
        } elseif ($usage < 1048576) {
            echo round($usage / 1024, 2), ' Kb', PHP_EOL;
        } else {
            echo round($usage / 1048576, 2), ' Mb', PHP_EOL;
        }

    }

    /**
     * @param $section
     */
    public static function stop($section)
    {
        if(getenv('REFILO_PROFILER') !== 'true') {
            return;
        }

        self::$level--;

        echo str_repeat('-', 1+ self::$level * 2), ' ' , $section, ' : ';
        self::memoryUsage();
    }
}
