<?php


namespace AutoAdmin\Bundle\Core\Helper;


class Probe
{
    protected static int $lastProbeTime = 0;
    protected static int $firstProbeTime = 0;

    protected static array $probeTimes = [];
    protected static array $probeLogs = [];

    public static function probe($silent = true): string
    {
        $probeTime = round(microtime(true) * 1000);
        if (self::$firstProbeTime === 0) {
            self::$firstProbeTime = self::$lastProbeTime = $probeTime;
        }

        $gap = $probeTime - self::$lastProbeTime;
        $fromStart = $probeTime - self::$firstProbeTime;

        self::$lastProbeTime = $probeTime;

        $bt = debug_backtrace();
        $caller = array_shift($bt);

        $file = $caller['file'];
        $line = $caller['line'];
        $log = ''
            . str_pad($file . '::' . $line, 100 - strlen((string)count(self::$probeLogs)), '.', STR_PAD_RIGHT)
            . ' '
            . str_pad($fromStart, 7, ' ', STR_PAD_LEFT) . 'ms'
            . ' '
            . '(+' . str_pad($gap, 4, ' ', STR_PAD_LEFT) . 'ms)';

        self::$probeTimes[$probeTime] = [
            'line' => $line,
            'file' => $file,
            'duration' => $gap,
        ];

        self::$probeLogs[] = $log;

        if (!$silent && function_exists('dump')) {
            dump($log);
        }

        return $log;
    }

    public static function getLogs(): array
    {
        return self::$probeLogs;
    }

    public static function reset(): void
    {
        self::$probeLogs = [];
    }

    public static function getCallerString($level = null): string
    {
        $db = debug_backtrace();

        if ($level !== null) {
            while ($level > 0) {
                $level--;
                $caller = array_shift($db);
            }
            $callerString = sprintf('%s:%s', $caller['file'], $caller['line']);
        } else {
            $callerString = '';
            foreach ($db as $caller) {
                $callerString .= "\n" . sprintf('%s:%s', $caller['file'], $caller['line']);
            }
        }

        return $callerString;
    }
}
