<?php declare(strict_types=1);

namespace Newland\Toubiz\Poi\Neos\ViewHelpers\Credentials;

use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Mvc\ActionRequest;
use Neos\FluidAdaptor\Core\ViewHelper\AbstractViewHelper;
use Newland\Toubiz\Poi\Neos\Service\OutdoorActiveCredentialsService;

/**
 * Assigns the outdoor active credentials for the current site to the template inside.
 *
 * @see OutdoorActiveCredentialsService
 * @example
 * <poi:credentials.outdoorActive as="outdoorActive">
 *      API KEY IS {outdoorActive.apiKey}
 * </poi:credentials.outdoorActive>
 */
class OutdoorActiveViewHelper extends AbstractViewHelper
{
    protected $escapeOutput = false;
    protected $escapeChildren = false;

    /**
     * @var OutdoorActiveCredentialsService
     * @Flow\Inject()
     */
    protected $credentialService;

    public function initializeArguments(): void
    {
        parent::initializeArguments();
        $this->registerArgument('as', 'string', 'Variable as which the configuration is assigned', true);
    }

    public function render(): string
    {
        $node = $this->node();
        if (!$node) {
            return '<!-- poi:credentials.outdoorActive: Node could not be found -->';
        }

        $credentials = $this->credentialService->getOutdoorActiveConfiguration($node);
        if ($credentials === null) {
            return '<!-- poi:credentials.outdoorActive: No credentials found in configuration -->';
        }

        $this->templateVariableContainer->add($this->arguments['as'], $credentials);
        $rendered = $this->renderChildren();
        $this->templateVariableContainer->remove($this->arguments['as']);

        return $rendered;
    }

    private function node(): ?NodeInterface
    {
        $request = $this->controllerContext->getRequest();
        if (!($request instanceof ActionRequest)) {
            return null;
        }

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

        return $node;
    }
}
