<?php

/*
 * This file is part of the "neos-common" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

namespace Newland\NeosCommon\Eel\Helper;

use Neos\ContentRepository\Domain\Model\Node;
use Neos\Flow\Annotations as Flow;
use Neos\Eel\ProtectedContextAwareInterface;
use Neos\Neos\Domain\Model\Site;
use Neos\Neos\Domain\Service\ContentContext;
use Newland\NeosCommon\Service\ConfigurationService;

class ConfigurationHelper implements ProtectedContextAwareInterface
{
    /**
     * @var ConfigurationService
     * @Flow\Inject()
     */
    protected $configurationService;

    /**
     * @param string $methodName
     * @return boolean
     */
    public function allowsCallOfMethod($methodName): bool
    {
        return true;
    }


    /**
     * @param Site|Node $siteOrNode
     * @param string|null $prefix
     * @param string|null $suffix
     * @return array|string|null
     */
    public function getSiteConfiguration($siteOrNode, ?string $prefix = '', ?string $suffix = '')
    {
        /** @var Site|null $site */
        $site = ($siteOrNode instanceof Node) ? $this->nodeToSite($siteOrNode) : $siteOrNode;
        $siteName = $site ? $site->getNodeName() : '';
        return $this->configurationService->getSiteConfiguration($siteName, (string) $prefix, (string) $suffix);
    }

    private function nodeToSite(Node $node): ?Site
    {
        $context = $node->getContext();
        if (!($context instanceof ContentContext)) {
            return null;
        }

        return $context->getCurrentSite();
    }
}
