<?php declare(strict_types=1);

namespace Newland\Toubiz\Poi\Neos\ViewHelpers\Splitscreen;

use Neos\Flow\Mvc\ActionRequest;
use Neos\FluidAdaptor\Core\ViewHelper\AbstractViewHelper;
use Neos\Flow\Annotations as Flow;
use Newland\Toubiz\Poi\Neos\Service\SplitscreenService;

class ConfigurationViewHelper extends AbstractViewHelper
{
    protected $escapeOutput = false;
    protected $escapeChildren = false;

    /**
     * @var SplitscreenService
     * @Flow\Inject()
     */
    protected $splitScreenService;

    /**
     * @param int $mainType
     * @param string $configurationAs
     * @return string
     */
    public function render(int $mainType, string $configurationAs): string
    {
        /** @var ActionRequest $request */
        $request = $this->controllerContext->getRequest();
        return $this->withAssignedVariables(
            [ $configurationAs => $this->splitScreenService->getConfiguration($request, $mainType) ],
            [ $this, 'renderChildren' ]
        );
    }

    private function withAssignedVariables(array $variables, callable $block)
    {
        $variableProvider = $this->renderingContext->getVariableProvider();

        foreach ($variables as $name => $content) {
            $variableProvider->add($name, $content);
        }

        $result = $block();

        foreach ($variables as $name => $content) {
            $variableProvider->remove($name);
        }

        return $result;
    }
}
