<?php declare(strict_types=1);

namespace Newland\NeosViewHelpers\ViewHelpers\Form;

use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\ContentRepository\Domain\Service\ContextFactoryInterface;
use Neos\Eel\FlowQuery\FlowQuery;
use Neos\Flow\Annotations as Flow;
use Neos\FluidAdaptor\Core\ViewHelper\AbstractViewHelper;
use Neos\Neos\Domain\Service\ContentContext;

/**
 * Viewhelper to render form fields from the node identifier
 */
class RenderLabelViewHelper extends AbstractViewHelper
{
    /**
     * @Flow\Inject
     * @var ContextFactoryInterface
     */
    protected $contextFactory;

    public function render(string $id): string
    {
        $node = $this->findFormNode($id);
        if ($node) {
            $property = $node->getProperty('label');

            if (!empty($property)) {
                return $property;
            }
        }
        return $id;
    }

    /**
     * Finds the node for the given id.
     *
     * @param string $id
     * @return \Neos\ContentRepository\Domain\Model\NodeInterface|null
     */
    protected function findFormNode($id): ?NodeInterface
    {
        $context = $this->contextFactory->create(
            [
                'workspaceName' => 'live',
                'currentDateTime' => new \Neos\Flow\Utility\Now(),
                'dimensions' => [],
                'invisibleContentShown' => false,
                'removedContentShown' => false,
                'inaccessibleContentShown' => false,
            ]
        );

        if ($context instanceof ContentContext) {
            return (new FlowQuery([ $context->getCurrentSiteNode() ]))
                ->find('#' . $id)
                ->get(0);
        }

        return null;
    }
}
