<?php

namespace Opentalent\OtTemplating\ViewHelpers\Template;


use Closure;
use Opentalent\OtCore\Exception\NoSuchWebsiteException;
use Opentalent\OtCore\ViewHelpers\OtAbstractViewHelper;
use Opentalent\OtCore\Website\OtWebsiteRepository;
use Opentalent\OtTemplating\Templating\TemplateRepository;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;

/**
 * Returns the value of the requested preference, or null if the key does not exist.
 *
 *     {namespace ot=Opentalent\OtTemplating\ViewHelpers}
 *
 *     {ot:template.preference('themeColor')}
 *
 * @package Opentalent\OtTemplating\ViewHelpers\Template
 */
class GetPreferenceViewHelper extends OtAbstractViewHelper
{
    public function __construct(
        private readonly OtWebsiteRepository $otWebsiteRepository,
        private readonly TemplateRepository $templateRepository,
    ) {}

    /**
     * -- This method is expected by Fluid --
     * Declares the viewhelper's parameters
     */
    public function initializeArguments(): void
    {
        $this->registerArgument(
            'key',
            'string',
            'The name of the requested preference',
            true
        );
    }

    /**
     * -- This method is expected by Fluid --
     * Renders the content as html
     *
     * @return string | null
     * @throws NoSuchWebsiteException
     */
    public function render(): ?string
    {
        $website = $this->otWebsiteRepository->getCurrentWebsiteFromFEGlobals();
        $preferences = $this->templateRepository->getTemplatePreferences($website);

        $key = $this->arguments['key'];
        return $preferences[$key] ?? null;
    }
}
