<?php
namespace Newland\Toubiz\Poi\Neos\ViewHelpers\Topic\Controller;

/*
 * This file is part of the "toubiz-poi-neos" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

use Neos\Flow\Annotations as Flow;
use Neos\FluidAdaptor\Core\Widget\AbstractWidgetController;
use Newland\NeosCommon\Domain\Model\Topic;
use Newland\Toubiz\Poi\Neos\Filter\ArticleFilterFactory;
use Newland\Toubiz\Poi\Neos\Service\RegionService;
use Newland\Toubiz\Sync\Neos\Domain\Repository\ArticleRepository;

class ArticlesController extends AbstractWidgetController
{
    /**
     * @var Topic
     */
    private $topic;
    /**
     * @var array
     */
    private $queryOverride = [];

    /**
     * @var array
     */
    private $properties = [];

    /**
     * @var ArticleRepository
     * @Flow\Inject()
     */
    protected $articleRepository;

    /**
     * @var RegionService
     * @Flow\Inject()
     */
    protected $regionService;

    public function indexAction(): void
    {
        $this->topic = $this->widgetConfiguration['topic'];
        $this->queryOverride = $this->widgetConfiguration['queryOverride'] ?? [];
        $this->properties = $this->widgetConfiguration['properties'] ?? [];
        $node = $this->widgetConfiguration['node'];

        $this->properties['preselectedCategories'][] = $this->topic->getIdentifier();
        $filter = (new ArticleFilterFactory($node))
            ->createFilterForArticleType($this->properties['articleType'], $this->properties)
            ->initializeForFilteredLists($this->request)
            ->setPageSize($this->widgetConfiguration['limit'] ?? 11);

        $count = $filter->countArticles();
        $articles = $filter
            ->getArticleQuery()
            ->setMaxResults($this->settings['gridItemsPerPage'])
            ->getQuery()
            ->execute();

        $this->view->assignMultiple(
            [
                'contentArguments' => [
                    'articles' => $articles,
                    'totalCount' => $count['items'],
                ],
            ]
        );
    }
}
