<?php

namespace Medienreaktor\Energize\ViewHelpers\News;


use GeorgRinger\News\Domain\Model\Dto\NewsDemand;
use GeorgRinger\News\Domain\Model\News;

class GetRelatedViewHelper extends \TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper {

    /**
     * @var bool
     */
    protected $escapeOutput = false;

    /**
     * newsRepository
     *
     * @var \GeorgRinger\News\Domain\Repository\NewsRepository
     */
    protected $newsRepository = null;
    public function __construct(\GeorgRinger\News\Domain\Repository\NewsRepository $newsRepository)
    {
        $this->newsRepository = $newsRepository;
    }

    /**
     * Arguments Initialization
     */
    public function initializeArguments(): void {
        $this->registerArgument('as', 'string', 'The variable name in which the data should be saved', TRUE);
        $this->registerArgument('newsItem', 'object', 'News Item to find related articles to ', TRUE);
        $this->registerArgument('newsDemand', 'object', 'NewsDemand object ', FALSE);
    }

    /**
     * Render method
     * @return string
     */
    public function render() {

        $as = $this->arguments['as'];
        /** @var News $newsItem */
        $newsItem = $this->arguments['newsItem'];
        /** @var NewsDemand $newsDemand */
        $newsDemand = $this->arguments['newsDemand'];

        if (!$newsDemand instanceof NewsDemand)
            $newsDemand = new NewsDemand();

        $categories = [];
        foreach ($newsItem->getCategories() as $category) {
            $categories[] = $category->getUid();
        }

        $newsDemand
            ->setCategories($categories)
            ->setCategoryConjunction("and")
            ->setExcludeAlreadyDisplayedNews(true)
            ->setOffset(0)
            ->setLimit(3);
        $newsList = $this->newsRepository->findDemanded($newsDemand);

        if ($newsList->count() < 3) {
            $newsDemand->setCategoryConjunction("or");
            $newsList = $this->newsRepository->findDemanded($newsDemand);
        }

        $this->templateVariableContainer->add($as, $newsList);
        $output = $this->renderChildren();
        $this->templateVariableContainer->remove($as);
        return $output;
    }


}
