<?php
/**
 * Demo Oracle — diagnostic d'un ralentissement (section « diag/slowdown »).
 *
 * Portage de modules/oracle/_report_diag_slowdown.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/slowdown');
$topWaits   = [];
$activeSess = [];
$topSql     = [];
$longOps    = [];

if (!$conn) {
    $fetchError = $ociError
        ? ('ORA-' . $ociError['code'] . ': ' . $ociError['message'])
        : t('demo_oracle.connect_error');
} else {
    $topWaits   = DemoOracleDiagRepository::slowdownGetTopWaits($conn);
    $activeSess = DemoOracleDiagRepository::slowdownGetActiveSessions($conn);
    $topSql     = DemoOracleDiagRepository::slowdownGetTopSql($conn);
    $longOps    = DemoOracleDiagRepository::slowdownGetLongOps($conn);

    oci_close($conn);
}

$fmtN = function ($n): string {
    $n = (float)$n;
    if ($n >= 1e12) return number_format($n / 1e12, 1, '.', ' ') . 'T';
    if ($n >= 1e9)  return number_format($n / 1e9,  1, '.', ' ') . 'G';
    if ($n >= 1e6)  return number_format($n / 1e6,  1, '.', ' ') . 'M';
    if ($n >= 1e3)  return number_format($n / 1e3,  1, '.', ' ') . 'K';
    return number_format($n, 0, '.', ' ');
};
$wcClass = function (string $wc): string {
    $map = [
        'User I/O'      => 'background:#1f77b4;color:#fff',
        'System I/O'    => 'background:#aec7e8;color:#000',
        'Concurrency'   => 'background:#d62728;color:#fff',
        'Application'   => 'background:#ff7f0e;color:#fff',
        'Commit'        => 'background:#9467bd;color:#fff',
        'Configuration' => 'background:#8c564b;color:#fff',
        'Cluster'       => 'background:#e377c2;color:#fff',
        'Network'       => 'background:#7f7f7f;color:#fff',
        'Other'         => 'background:#bcbd22;color:#000',
        'CPU'           => 'background:#2ca02c;color:#fff',
    ];
    return $map[$wc] ?? 'background:#888;color:#fff';
};
View::display(__DIR__ . '/views/report/diag_slowdown.php', [
    'fetchError' => $fetchError,
    'topWaits'   => $topWaits,
    'activeSess' => $activeSess,
    'topSql'     => $topSql,
    'longOps'    => $longOps,
    'fmtN'       => $fmtN,
    'wcClass'    => $wcClass,
]);
