<?php declare(strict_types=1);

namespace Newland\NeosViewHelpers\ErrorHandling;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Log\ThrowableStorageInterface;
use Neos\Flow\Utility\Environment;

/**
 * @Flow\Scope("singleton")
 */
class ViewErrorHandler
{

    /**
     * @var ThrowableStorageInterface
     * @Flow\Inject()
     */
    protected $exceptionLogger;

    /**
     * @var bool|null
     * @Flow\InjectConfiguration("throwOnPartialError")
     */
    protected $throwOnPartialError;

    /**
     * @var Environment
     * @Flow\Inject()
     */
    protected $environment;

    public function handleErrorInClosure(\Closure $closure, ?string $errorHeader = null)
    {
        try {
            return $closure();
        } catch (\Throwable $error) {
            return $this->handleError($error, $errorHeader);
        }
    }

    public function handleError(\Throwable $error, ?string $errorHeader): string
    {
        if ($this->shouldThrow()) {
            throw $error;
        }
        try {
            return $this->logErrorAndReturnMessage($error, $errorHeader);
        } catch (\Throwable $inner) {
            throw new \Exception($inner->getMessage(), $error->getCode(), $error);
        }
    }

    protected function logErrorAndReturnMessage(\Throwable $error, ?string $errorHeader): string
    {
        $info = $this->exceptionLogger->logThrowable($error);
        if ($errorHeader === null) {
            return $info;
        }
        return sprintf('<strong>%s</strong> <hr> <small>%s</small>', $errorHeader, $info);
    }

    protected function shouldThrow(): bool
    {
        if (\is_bool($this->throwOnPartialError)) {
            return $this->throwOnPartialError;
        }

        return !$this->environment->getContext()->isProduction();
    }
}
