<?php declare(strict_types=1);

namespace Newland\NeosViewHelpers\ViewHelpers;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Core\Bootstrap;
use Neos\Flow\Log\PsrSystemLoggerInterface;
use Newland\NeosViewHelpers\ErrorHandling\ViewErrorHandler;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\ViewHelpers\RenderViewHelper as FluidRenderViewHelper;

/**
 * Wrapper around the f:render viewhelper that handles errors depending on the current environment.
 * This is being done to have a more reliable production version in which an error in a partial does
 * not break the whole site - but only that one partial.
 *
 * The behaviour can be influenced in the `Newland.NeosViewHelpers.throwOnPartialError` configuration
 * in your global `Configuration/Settings.yaml`. By default this configuration is false for production
 * environments and true for development.
 */
class RenderViewHelper extends FluidRenderViewHelper
{

    /**
     * @var PsrSystemLoggerInterface
     * @Flow\Inject()
     */
    protected $log;

    public static function renderStatic(
        array $arguments,
        \Closure $renderChildrenClosure,
        RenderingContextInterface $renderingContext
    ) {
        /** @var ViewErrorHandler $handler */
        $handler = Bootstrap::$staticObjectManager->get(ViewErrorHandler::class);
        return $handler->handleErrorInClosure(
            function () use ($arguments, $renderChildrenClosure, $renderingContext) {
                return parent::renderStatic($arguments, $renderChildrenClosure, $renderingContext);
            },
            static::getHeader($arguments)
        );
    }

    protected static function getHeader(array $arguments): string
    {
        if (!empty($arguments['section'])) {
            $type = 'section';
        } elseif (!empty($arguments['partial'])) {
            $type = 'partial';
        } else {
            $type = '';
        }

        $thing = $arguments[$type] ?? '';
        return sprintf('Error rendering %s %s', $type, $thing);
    }
}
