<?php declare(strict_types=1);

namespace Newland\Toubiz\Common\Neos\ViewHelpers\Slot;

use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Fusion\Core\Runtime;
use Neos\Neos\Domain\Service\FusionService;
use Newland\NeosCommon\Service\ControllerContextFactory;
use Newland\NeosCommon\Service\NodeService;

/**
 * Manages fusion runtimes for the slot rendering viewhelper.
 * Note, that these runtimes are not universally usable as they have a very limited scope and are
 * initialized with faked controller contexts in order to be easily cacheable.
 *
 * @Flow\Scope("singleton")
 */
class FusionRuntimeManager
{

    /**
     * @var FusionService
     * @Flow\Inject()
     */
    protected $fusionService;

    /**
     * @var NodeService
     * @Flow\Inject()
     */
    protected $nodeService;

    /**
     * @var ControllerContextFactory
     * @Flow\Inject()
     */
    protected $controllerContextFactory;

    /** @var array<string, Runtime> */
    protected $runtimes = [];

    public function runtime(NodeInterface $node): Runtime
    {
        $siteNode = $this->nodeService->getCurrentSiteNode($node);
        $path = $siteNode->getPath();

        if (!array_key_exists($path, $this->runtimes)) {
            $this->runtimes[$path] = $this->fusionService->createRuntime(
                $this->nodeService->getCurrentSiteNode($node),
                $this->controllerContextFactory->initializeFakeControllerContext($siteNode)
            );
        }

        return $this->runtimes[$path];
    }
}
