<?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\Service;

use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Configuration\ConfigurationManager;
use Newland\NeosCommon\Exceptions\UnknownSiteException;

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

    /**
     * @var ConfigurationManager
     * @Flow\Inject()
     */
    protected $configurationManager;

    /**
     * This method can get a site specific configuration value. The settings need to follow
     * this convention - `default` and `sites` key must be used:
     *
     * myConfigSetting:
     *   default: myDefaultValue
     *   sites:
     *     mySiteKey: mySiteSpecificValue
     *     myOtherSiteKey: myOtherSiteSpecificValue
     *
     * @param string $siteKey
     * @param string $prefix
     * @param string $suffix
     * @return array|string|null
     */
    public function getSiteConfiguration(string $siteKey, string $prefix = '', string $suffix = '')
    {
        $configurationPath = $this->getConfigurationPath($prefix, $siteKey, $suffix);

        $value = $this->configurationManager->getConfiguration(
            ConfigurationManager::CONFIGURATION_TYPE_SETTINGS,
            $configurationPath
        );

        if (empty($value)) {
            $configurationPath = $this->getConfigurationPath($prefix, 'default', $suffix);
            $value = $this->configurationManager->getConfiguration(
                ConfigurationManager::CONFIGURATION_TYPE_SETTINGS,
                $configurationPath
            );
        }

        return $value;
    }

    /** @return array|string|null */
    public function getCurrentSiteConfiguration(NodeInterface $node, string $prefix = '', string $suffix = '')
    {
        try {
            $siteKey = 'sites.' . $this->nodeService->getCurrentSiteNodeName($node);
        } catch (UnknownSiteException $e) {
            $siteKey = 'default';
        }

        return $this->getSiteConfiguration($siteKey, $prefix, $suffix);
    }

    /** @return array|string|null */
    public function getConfiguration(string $configurationPath)
    {
        return $this->configurationManager->getConfiguration(
            ConfigurationManager::CONFIGURATION_TYPE_SETTINGS,
            $configurationPath
        );
    }

    private function getConfigurationPath(string $prefix, string $siteKey, string $suffix): string
    {
        $configurationPath = '';

        if ($prefix) {
            $configurationPath = trim($prefix, '.') . '.';
        }

        $configurationPath .= $siteKey;

        if ($suffix) {
            $configurationPath .= '.' . trim($suffix, '.');
        }
        return $configurationPath;
    }
}
