<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers;

use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Extbase\Service\ExtensionService;

trait ViewHelperTrait
{
    /**
     * @var ExtensionService
     */
    protected $extensionService;

    protected $prefix = null;

    /**
     * @param ExtensionService $extensionService
     */
    public function injectExtensionService(ExtensionService $extensionService): void
    {
        $this->extensionService = $extensionService;
    }
    protected function getRequest(): ?ServerRequestInterface
    {
        $request = null;
        if ($this->renderingContext->hasAttribute(ServerRequestInterface::class)) {
            $request = $this->renderingContext->getAttribute(ServerRequestInterface::class);
        }
        return $request;
    }

    /**
     * Returns the prefix for link arguments
     */
    public function getLinkPrefix()
    {
        if ($this->prefix == null) {
            $request = $this->getRequest();
            $extensionName = $request->getControllerExtensionName();
            $pluginName = $request->getPluginName();
            if ($extensionName !== null && $pluginName != null) {
                $this->prefix = $this->extensionService->getPluginNamespace($extensionName, $pluginName);
            } else {
                $this->prefix = '';
            }
        }
        return $this->prefix;
    }
}
