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

/*
 * 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\ContentRepository\Domain\Model\Node;
use Neos\Eel\FlowQuery\FlowQuery;
use Neos\FluidAdaptor\Core\ViewHelper\AbstractViewHelper;
use Newland\NeosCommon\Service\ContextService;
use Neos\Flow\Annotations as Flow;

/**
 * Toubiz map node view helper.
 *
 * Returns the document/page node that contains a toubiz map.
 */
class ToubizMapNodeViewHelper extends AbstractViewHelper
{
    /**
     * @var ContextService
     * @Flow\Inject()
     */
    protected $contextService;

    /**
     * This may also return null in case no page contains a toubiz map.
     *
     * @return Node|null
     */
    public function render(): ?Node
    {
        $site = $this->contextService->siteNodeFromControllerContext($this->controllerContext);
        return (new FlowQuery([ $site ]))
            ->find('[instanceof Newland.Toubiz.Map.Neos:Map]')
            ->parents('[instanceof Neos.NodeTypes:Page]')
            ->get(0);
    }
}
