<?php

function getDB(): engine\MySQL|null {
    global $config;

    /** @var ?engine\MySQL $link */
    static $link = null;
    if (!is_null($link))
        return $link;

    $link = new engine\MySQL(
        $config['mysql']['host'],
        $config['mysql']['user'],
        $config['mysql']['password'],
        $config['mysql']['database']);
    if (!$link->connect()) {
        if (!isCli()) {
            header('HTTP/1.1 503 Service Temporarily Unavailable');
            header('Status: 503 Service Temporarily Unavailable');
            header('Retry-After: 300');
            die('database connection failed');
        } else {
            fwrite(STDERR, 'database connection failed');
            exit(1);
        }
    }

    return $link;
}

function getMC(): Memcached {
    static $mc = null;
    if ($mc === null) {
        $mc = new Memcached();
        $mc->addServer("127.0.0.1", 11211);
    }
    return $mc;
}

function logDebug(...$args): void {
    global $globalContext;
    $globalContext->logger->log(engine\logging\LogLevel::DEBUG, null, ...$args);
}

function logWarning(...$args): void {
    global $globalContext;
    $globalContext->logger->log(engine\logging\LogLevel::WARNING, null, ...$args);
}

function logError(...$args): void {
    global $globalContext;
    if (array_key_exists('stacktrace', $args)) {
        $st = $args['stacktrace'];
        unset($args['stacktrace']);
    } else {
        $st = null;
    }
    if ($globalContext->logger->canReport())
        $globalContext->logger->log(engine\logging\LogLevel::ERROR, $st, ...$args);
}

function lang(...$args) {
    global $globalContext;
    return $globalContext->getStrings()->get(...$args);
}

function langNum(...$args) {
    global $globalContext;
    return $globalContext->getStrings()->num(...$args);
}

function isDev(): bool { global $globalContext; return $globalContext->isDevelopmentEnvironment; }
function isCli(): bool { return PHP_SAPI == 'cli'; };
function isRetina(): bool { return isset($_COOKIE['is_retina']) && $_COOKIE['is_retina']; }
function isXHRRequest() { return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'; }

function isAdmin(): bool {
    if (app\Admin::getId() === null)
        app\Admin::check();
    return app\Admin::getId() != 0;
}

function getExecutionTime(): float {
    $exec_time = microtime(true) - START_TIME;
    return round($exec_time, 4);
}