<?php declare(strict_types=1);

namespace Newland\Toubiz\Poi\Neos\Service;

use Neos\Flow\Mvc\ActionRequest;
use Newland\NeosIcons\IconUrlService;
use Newland\Toubiz\Poi\Neos\Service\MapCompatibility\ApiKeyService;
use Neos\Flow\Annotations as Flow;

class SplitscreenService
{

    /**
     * @var array
     * @Flow\InjectConfiguration(package="Newland.Toubiz.Poi.Neos", path="splitscreen")
     */
    protected $configuration;

    /**
     * @var IconUrlService
     * @Flow\Inject()
     */
    protected $iconUrlService;

    /**
     * @var array
     * @Flow\InjectConfiguration(package="Newland.Toubiz.Map.Neos", path="clustering")
     */
    protected $mapClusteringSettings;

    /**
     * @var ApiKeyService
     * @Flow\Inject()
     */
    protected $apiKeyService;

    private $cache = [];

    public function isEnabled(int $mainType): bool
    {
        return $this->configuration['mainType'][$mainType]['enabled']
            ?? $this->configuration['default']['enabled']
            ?? false;
    }

    public function getConfiguration(ActionRequest $request, int $mainType): array
    {
        if (!array_key_exists($mainType, $this->cache)) {
            $this->cache[$mainType] = array_replace_recursive(
                $this->configuration['default'],
                $this->configuration['mainType'][$mainType] ?? []
            );

            $this->cache[$mainType]['marker']['iconUrl'] = $this->iconUrlService->buildMarkerIconUrl(
                $this->cache[$mainType]['marker'] ?? [],
                $request
            );

            $this->cache[$mainType]['clustering']['color'] =
                $this->cache[$mainType]['clustering']['color']
                ?? $this->mapClusteringSettings['color'];

            $this->cache[$mainType]['clustering']['backgroundColor'] =
                $this->cache[$mainType]['clustering']['backgroundColor']
                ?? $this->mapClusteringSettings['backgroundColor'];

            $this->cache[$mainType]['apiKeys'] = $this->apiKeyService->getApiKeys($request);
        }

        return $this->cache[$mainType];
    }
}
