<?php declare(strict_types=1);

namespace Newland\Toubiz\Map\Neos\Service;

use Neos\ContentRepository\Domain\Model\NodeInterface;
use Newland\NeosCommon\Service\ConfigurationService;
use Neos\Flow\Annotations as Flow;

/**
 * @Flow\Scope("singleton")
 */
class ApiKeyService
{

    /**
     * @var ConfigurationService
     * @Flow\Inject()
     */
    protected $configurationService;

    public function getApiKeys(NodeInterface $node): array
    {
        $apiKeys = $this->configurationService->getCurrentSiteConfiguration(
            $node,
            'Newland.Toubiz.Map.Neos.apiKeys'
        );

        if (!empty($apiKeys)) {
            return $apiKeys;
        }

        return $this->getLegacyApiKeys($node) ?? [];
    }

    private function getLegacyApiKeys(NodeInterface $node): ?array
    {
        $googleMapsKey = $this->configurationService->getCurrentSiteConfiguration(
            $node,
            'Newland.Toubiz.Map.Neos.services.map.apiKey'
        );

        if (!empty($googleMapsKey)) {
            return [ 'googleMaps' => $googleMapsKey ];
        }

        $key = $this->configurationService->getConfiguration('Newland.Toubiz.Map.Neos.apiKey');
        if ($key) {
            return [ 'googleMaps' => $key ];
        }

        return null;
    }
}
