<?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;

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

    public function initializeArguments(): void
    {
        $this->registerUniversalTagAttributes();
        $this->registerArgument('query', 'array', 'The search query array', true);
    }

    public function render(): string
    {
        if (!$this->isInBackend()) {
            $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();
        }
        return '';
    }

    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();
    }
}
