<?php declare(strict_types=1);
namespace Newland\Toubiz\Poi\Neos\ViewHelpers\OpeningTimes;

use Neos\FluidAdaptor\Core\ViewHelper\AbstractViewHelper;
use Newland\Toubiz\Poi\Neos\OpeningTimes\Parser\KitchenTimes\LegacyFormatParser;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;

class KitchenTimesViewHelper extends AbstractViewHelper
{
    use CompileWithRenderStatic;

    protected $escapeOutput = false;

    public function initializeArguments()
    {
        parent::initializeArguments();
        $this->registerArgument('openingTimes', 'string', 'The raw json data of the opening times.', true);
        $this->registerArgument('openingTimesFormat', 'string', 'The format of the opening times.', false, 'legacy');
        $this->registerArgument('as', 'string', 'The template variable name.', true);
    }

    public static function renderStatic(
        array $arguments,
        \Closure $renderChildrenClosure,
        RenderingContextInterface $renderingContext
    ): string {
        $templateVariableContainer = $renderingContext->getVariableProvider();

        switch ($arguments['openingTimesFormat']) {
            case 'legacy':
                $parser = new LegacyFormatParser();
                break;
            default:
                throw new \Exception(
                    sprintf('No parser found for opening times format "%s".', $arguments['openingTimesFormat'])
                );
                break;
        }

        $openingTimes = $parser->parse($arguments['openingTimes']);
        $templateVariableContainer->add($arguments['as'], $openingTimes);
        $output = $renderChildrenClosure();
        $templateVariableContainer->remove($arguments['as']);

        return $output;
    }
}
