<?php
declare(strict_types=1);

namespace Uhura\Grossmarkt\ViewHelpers\Resource;

use GeorgRinger\News\Domain\Model\Dto\NewsDemand;
use GeorgRinger\News\Domain\Repository\NewsRepository;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

class GetNewsItemsViewHelper extends AbstractViewHelper
{

    public static function getContainer(): ContainerInterface
    {
        return GeneralUtility::getContainer();
    }

    /**
     * initialize arguments
     */
    public function initializeArguments(): void
    {
        $this->registerArgument('pid', 'string', 'PID', false, 0);
        $this->registerArgument('limit', 'int', 'Limit');
    }

    /**
     *
     * @param array $arguments
     * @param \Closure $renderChildrenClosure
     * @param RenderingContextInterface $renderingContext
     * @return mixed
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function renderStatic(
        array $arguments,
        \Closure $renderChildrenClosure,
        RenderingContextInterface $renderingContext
    )
    {
        /* @var $demand NewsDemand */
        $demand = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(NewsDemand::class);
        $demand->setStoragePage((string)$arguments['pid']);
        if (!empty($arguments['limit'])) {
            $demand->setLimit((int)$arguments['limit']);
        }
        $newsRepository = self::getContainer()->get(NewsRepository::class);
        return $newsRepository->findDemanded($demand);
    }
}