<?php
/**
 * Demo Oracle — diagnostic ORA-04030 (memoire процесс PGA) (section « diag/ora4030 »).
 *
 * Portage de modules/oracle/_report_diag_ora04030.php, sans retrait :
 * ce rapport est une lecture pure, et le module complet n'y propose aucune
 * action. La demonstration le sert donc a l'identique.
 *
 * Inclus par report.php. Variables : $oraDb, $db, $currentUser, $settings.
 */

require_once __DIR__ . '/lib/DemoOracleOciConnect.php';
require_once __DIR__ . '/lib/DemoOracleDiagRepository.php';

/** @var array      $oraDb       */
/** @var Database   $db          */
/** @var array|null $currentUser */

$ociError   = null;
$fetchError = null;
$conn       = demo_oracle_oci_open($oraDb, $db, $ociError, '', 'diag/ora04030');
$pgaStat    = [];
$params     = [];
$topProc    = [];
$pgaCateg   = [];

if (!$conn) {
    $fetchError = $ociError
        ? ('ORA-' . $ociError['code'] . ': ' . $ociError['message'])
        : t('demo_oracle.connect_error');
} else {
    $params   = DemoOracleDiagRepository::ora4030GetPgaParams($conn);
    $pgaStat  = DemoOracleDiagRepository::ora4030GetPgaStats($conn);
    $topProc  = DemoOracleDiagRepository::ora4030GetTopProcesses($conn);
    $pgaCateg = DemoOracleDiagRepository::ora4030GetMemoryByCategory($conn);

    oci_close($conn);
}

$fmtBytes = function ($b): string {
    $b = (float)$b;
    if ($b >= 1073741824) return number_format($b / 1073741824, 2, '.', ' ') . ' GB';
    if ($b >= 1048576)    return number_format($b / 1048576,    1, '.', ' ') . ' MB';
    if ($b >= 1024)       return number_format($b / 1024,       1, '.', ' ') . ' KB';
    return number_format($b, 0, '.', ' ') . ' B';
};
$g = function (string $k) use ($pgaStat): float { return (float)($pgaStat[$k] ?? 0); };
$overAlloc = $g('over allocation count');
View::display(__DIR__ . '/views/report/diag_ora04030.php', [
    'fetchError' => $fetchError,
    'params'     => $params,
    'pgaStat'    => $pgaStat,
    'topProc'    => $topProc,
    'pgaCateg'   => $pgaCateg,
    'fmtBytes'   => $fmtBytes,
    'g'          => $g,
    'overAlloc'  => $overAlloc,
]);
