<?php
namespace Newland\Toubiz\Events\Neos\Controller;

/*
 * This file is part of the "toubiz-events-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\ContentRepository\Domain\Model\Node;
use Newland\NeosCommon\Utility\PaginationUtility;
use Newland\Toubiz\Events\Neos\Filter\EventDateFilterFactory;
use Newland\Toubiz\Events\Neos\Filter\Items\EventDateRoot;
use Psr\Http\Message\UriInterface;

class FilteredListsController extends AbstractActionController
{
    /**
     * @var PaginationUtility
     * @Flow\Inject()
     */
    protected $paginationUtility;

    public function showAction(Node $node = null): void
    {
        // For AJAX requests we need to set the node manually and re-parse the properties, etc.
        if ($node !== null) {
            $this->setupCustomNodeMappingForAjaxRequest($node);
            $this->initializeNode($node);
        }

        $override = $this->properties;
        if ($this->properties['showTodaySeparately'] ?? false) {
            $override['numberOfDays'] = [
                'from' => (clone $this->now)->modify('+1 day')->format('Y-m-d'),
            ];
        }

        $filter = (new EventDateFilterFactory($this->node))
            ->createEventFilter($this->settings['filter'], $override)
            ->initializeForFilteredLists($this->request);

        $eventDates = $filter
            ->getEventQuery()
            ->setMaxResults($this->settings['itemsPerPage'])
            ->getQuery()
            ->execute();

        $pagination = $this->paginationUtility->getPaginationData(
            $filter->countResults(),
            $this->getCurrentPageNumberFromRequest(),
            $this->settings['itemsPerPage']
        );

        $this->view->assignMultiple(
            [
                'filter' => $filter,
                'eventDates' => $eventDates,
                'format' => $node ? 'ajax' : 'html',
                'listLinks' => $this->request->getInternalArgument('__listLinks'),
                'listLinksTitle' => $this->properties['listLinksTitle'] ?? '',
                'pagination' => $pagination,
                'secondPageUri' => $this->secondPageUri(),
                'displayAsTeaserList' => $this->properties['displayAsTeaserList'] ?? false,
            ]
        );
    }

    public function linkAction(): void
    {
        $filter = (new EventDateFilterFactory($this->node))
            ->createEventFilter($this->settings['filter'], $this->properties)
            ->initializeForFilteredLists($this->request);

        $this->view->assignMultiple(
            [
                'listUri' => $filter->getListUri($this->getControllerContext(), $this->properties),
                'title' => $this->properties['title'] ?? '',
            ]
        );
    }

    private function getCurrentPageNumberFromRequest(string $argument = 'page'): int
    {
        if (!$this->request->getMainRequest()->hasArgument($argument)) {
            return 1;
        }

        return max(1, (int) $this->request->getMainRequest()->getArgument($argument));
    }

    private function secondPageUri(): UriInterface
    {
        $uri = $this->request->getHttpRequest()->getUri();
        if ($uri->getQuery() === '') {
            return $uri->withQuery('page=2');
        }
        return $uri->withQuery($uri->getQuery() . '&page=2');
    }
}
