<?php

namespace engine\logging;

class Util
{
    public static function getPHPErrorName(int $errno): ?string {
        static $errors = null;
        if (is_null($errors))
            $errors = array_flip(array_slice(get_defined_constants(true)['Core'], 0, 15, true));
        return $errors[$errno] ?? null;
    }

    public static function strVarDump($var, bool $print_r = false): string {
        ob_start();
        $print_r ? print_r($var) : var_dump($var);
        return trim(ob_get_clean());
    }

    public static function strVars(array $args): string {
        $args = array_map(fn($a) => match (gettype($a)) {
            'string' => $a,
            'array', 'object' => self::strVarDump($a, true),
            default => self::strVarDump($a)
        }, $args);
        return implode(' ', $args);
    }

    public static function backtraceAsString(int $shift = 0): string {
        $bt = debug_backtrace();
        $lines = [];
        foreach ($bt as $i => $t) {
            if ($i < $shift)
                continue;

            if (!isset($t['file'])) {
                $lines[] = 'from ?';
            } else {
                $lines[] = 'from '.$t['file'].':'.$t['line'];
            }
        }
        return implode("\n", $lines);
    }

    public static function ansi(string     $text,
                                ?AnsiColor $fg = null,
                                ?AnsiColor $bg = null,
                                bool       $bold = false,
                                bool       $fg_bright = false,
                                bool       $bg_bright = false): string {
        $codes = [];
        if (!is_null($fg))
            $codes[] = $fg->value + ($fg_bright ? 90 : 30);
        if (!is_null($bg))
            $codes[] = $bg->value + ($bg_bright ? 100 : 40);
        if ($bold)
            $codes[] = 1;

        if (empty($codes))
            return $text;

        return "\033[".implode(';', $codes)."m".$text."\033[0m";
    }

    public static function getErrorFullStackTrace(\Throwable $error): string {
        return '#_ '.$error->getFile().'('.$error->getLine().')'."\n".$error->getTraceAsString();
    }
}