<?php
require_once __DIR__ . '/Encription.php';


class TestResultsManager
{

    private $encriptor;


    private $resultsFile = './test_results';

    public function __construct()
    {
        $this->encriptor = new Encription();
    }


    private function loadAllTestResults()
    {
        if (file_exists($this->resultsFile)) {
            $decryptedJson = $this->encriptor->loadDecryptedJson($this->resultsFile);
            return json_decode($decryptedJson, true);
        }
        return [];
    }

    private function loadTestResults($testName)
    {
        $allResults = $this->loadAllTestResults();
        return $allResults[$testName] ?? [];
    }

    private function saveTestResults($testName, $results)
    {
        $allResults = $this->loadAllTestResults();
        $allResults[$testName] = $results;
        $this->encriptor->saveEncryptedJson($this->resultsFile, json_encode($allResults));
    }

    private function getImprovementNum($testCase)
    {
        $savedResult = $this->loadTestResults($testCase);
        return $savedResult['improvement'] ?? 0;
    }

    private function saveCurrentTestResults($testCase, $testResults)
    {
        $savedResult = $this->loadTestResults($testCase);
        $lem = $savedResult['LEM'] ?? null;

        if ($lem != $testResults['LEM'] && $lem != null) {
            $testResults['improvement']++;
        }

        $this->saveTestResults($testCase, $testResults);

        fwrite(STDOUT, "\n" . "Perbaikan " . $testCase . " : " . $testResults['improvement'] . "\n");
    }

    public function showTestResult($testCase, $exception = null): void
    {
        $testResults = [
            'status' => $exception == null ? 'passed' : 'failed',
            'LEM' => $exception == null ? '' : $exception->getTraceAsString(),
            'improvement' => $this->getImprovementNum($testCase),
        ];

        $this->saveCurrentTestResults($testCase, $testResults);
    }
}
