<?php
namespace Newland\Toubiz\Poi\Neos\ViewHelpers\Link;

use Neos\ContentRepository\Domain\Model\Node;
use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Mvc\ActionRequest;
use Neos\FluidAdaptor\Core\ViewHelper\AbstractTagBasedViewHelper;
use Neos\Neos\Domain\Service\ContentContext;
use Newland\Toubiz\Poi\Neos\Filter\Items\ArticleRoot;

class ArticleFilterViewHelper extends AbstractTagBasedViewHelper
{
    protected $tagName = 'a';

    public function initializeArguments(): void
    {
        $this->registerUniversalTagAttributes();
        $this->registerArgument('query', 'array', 'The search query array', true);
        $this->registerArgument(
            'filter',
            'object',
            'The currently displayed filter',
            true
        );
        $this->registerArgument(
            'countAs',
            'string',
            'variable to which the count is going to be assigned to',
            false
        );
    }

    public function render(): string
    {
        if ($this->isInBackend()) {
            return '';
        }

        if ($this->arguments['countAs'] ?? false) {
            $this->renderingContext->getVariableProvider()->add($this->arguments['countAs'], $this->getCount());
        }

        $uri = (clone $this->controllerContext->getUriBuilder())
            ->reset()
            ->setFormat('html')
            ->setArguments($this->arguments['query'])
            ->uriFor(
                'show',
                [],
                'FilteredLists',
                'Newland.Toubiz.Poi.Neos'
            );

        $this->tag->setContent($this->renderChildren());
        $this->tag->addAttribute('href', $uri);


        return $this->tag->render();
    }

    private function isInBackend(): bool
    {
        $request = $this->controllerContext->getRequest();
        if (!($request instanceof ActionRequest)) {
            return false;
        }

        /** @var NodeInterface|null $node */
        $node = $request->getInternalArgument('__node');
        $context = null;
        if ($node instanceof Node) {
            $context = $node->getContext();
        }

        if (!($context instanceof ContentContext)) {
            return false;
        }

        return $context->isInBackend();
    }

    private function getCount(): int
    {
        /** @var ArticleRoot $filter */
        $filter = clone $this->arguments['filter'];
        $filter->setState($this->arguments['query']);
        return $filter->countArticles();
    }
}
