<?php declare(strict_types=1);

namespace Newland\Toubiz\Poi\Neos\Service\MapCompatibility;

use Neos\ContentRepository\Domain\Model\Node;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Mvc\ActionRequest;
use Neos\Flow\Mvc\RequestInterface;
use Neos\Flow\ObjectManagement\ObjectManager;
use Newland\NeosCommon\Service\ConfigurationService;
use Newland\Toubiz\Map\Neos\Service\ApiKeyService as MapPackageApiKeyService;

/**
 * Small wrapper around the ApiKeyService of the maps package that uses the original version
 * if it is available and falls back to API Keys defined in `Newland.Toubiz.Poi.Neos.apiKeysForUseWithoutMapsPackage`
 * if not.
 *
 * @Flow\Scope("singleton")
 */
class ApiKeyService
{

    /**
     * @var ObjectManager
     * @Flow\Inject()
     */
    protected $objectManager;

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

    public function getApiKeys(RequestInterface $request): array
    {
        /** @var Node|null $node */
        $node = ($request instanceof ActionRequest) ? $request->getInternalArgument('__node') : null;

        if ($node && class_exists(MapPackageApiKeyService::class)) {
            /** @var MapPackageApiKeyService $apiKeyService */
            $apiKeyService = $this->objectManager->get(MapPackageApiKeyService::class);
            return $apiKeyService->getApiKeys($node);
        }

        if ($node) {
            return (array) $this->configurationService->getCurrentSiteConfiguration(
                $node,
                'Newland.Toubiz.Poi.Neos.apiKeysForUseWithoutMapsPackage'
            );
        }

        return [];
    }
}
