<?php

namespace Velis\Debugger\Module;

use Throwable;
use Velis\Debugger\Dto\DebuggerExceptionDto;
use Velis\Dto\BaseDto;

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

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

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

    public function handle(): void
    {
        $this->result = DebuggerExceptionDto::fromArray([
            'message' => $this->exception->getMessage(),
            'code' => $this->exception->getCode(),
            'file' => $this->exception->getFile(),
            'line' => $this->exception->getLine(),
            'trace' => $this->exception->getTrace(),
            'previous' => $this->getPrevious(),
        ]);

        $this->isInitialized = true;
    }

    /**
     * Recursively get previous exceptions.
     */
    protected function getPrevious(): ?BaseDto
    {
        if (!$this->exception->getPrevious() instanceof Throwable) {
            return null;
        }

        $debuggerExceptionModule = new DebuggerExceptionModule($this->exception->getPrevious());
        $debuggerExceptionModule->handle();

        return $debuggerExceptionModule->getResult();
    }
}
