<?php

namespace Velis\Debugger\Module;

use Api\RestfulProfiler;
use Velis\App;
use Velis\Debugger\Dto\DebuggerProfilerDto;
use Velis\Dto\BaseDto;

/**
 * @author Szymon Janaczek <szymon.janaczek@velistech.com>
 */
class DebuggerProfilerModule extends AbstractDebuggerModule
{
    public DebuggerProfilerDto $result;

    public static function getModuleName(): string
    {
        return 'profiler';
    }

    public function getResult(): BaseDto
    {
        return $this->result;
    }

    public function handle(): void
    {
        if (!App::$config->settings->debug?->profiler) {
            return;
        }

        $this->result = $this->getProfiler();

        $this->isInitialized = true;
    }

    public function getProfiler(): DebuggerProfilerDto
    {
        $profiler = (new RestfulProfiler())->getProfiler();

        $params = [];
        if (is_array($profiler['db'])) {
            $params['database'] = $profiler['db'];
        }

        if (is_array($profiler['cache'])) {
            $params['cache'] = $profiler['cache'];
        }

        if (is_array($profiler['included_files'])) {
            $params['included_files'] = $profiler['included_files'];
        }

        if (is_array($profiler['checked_privs'])) {
            $params['checked_privs'] = $profiler['checked_privs'];
        }

        foreach ($profiler as $key => $value) {
            if (str_starts_with($key, 'included files')) {
                $params['included_files'] = $value;
                break;
            }
        }

        return DebuggerProfilerDto::fromArray($params);
    }
}
