<?php declare(strict_types=1);

namespace Newland\Toubiz\Poi\Neos\ViewHelpers;

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

class StaticMapViewHelper extends AbstractTagBasedViewHelper
{

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

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

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

    public function render(
        float $latitude,
        float $longitude,
        int $width = 800,
        int $height = 600,
        int $zoom = 75,
        string $mapType = null
    ): string {
        $mapType = $mapType ?? $this->staticMapConfiguration['mapType'] ?? null;

        if ($mapType === null) {
            return '<!-- Static map not rendered: No map type defined. -->';
        }

        /** @var ActionRequest $request */
        $request = $this->controllerContext->getRequest();
        $iconUrl = $this->iconUrlService->buildMarkerIconUrl(
            $this->staticMapConfiguration['style'] ?? [],
            $request
        );
        $this->addApiKeysToTags();
        $this->tag->addAttributes(
            [
                'class' => 'cursor-pointer',
                'data-toubiz-static-map' => '',
                'data-toubiz-static-map.map-type' => $mapType,
                'data-toubiz-static-map.map.zoom' => $zoom,
                'data-toubiz-static-map.width' => $width,
                'data-toubiz-static-map.height' => $height,
                'data-toubiz-static-map.markers.0.icon-url' => $iconUrl,
                'data-toubiz-static-map.markers.0.latitude' => $latitude,
                'data-toubiz-static-map.markers.0.longitude' => $longitude,
            ]
        );

        $this->tag->forceClosingTag(true);
        return $this->tag->render();
    }

    private function addApiKeysToTags(): void
    {
        $apiKeys = $this->apiKeyService->getApiKeys($this->controllerContext->getRequest());

        if (array_key_exists('googleMaps', $apiKeys)) {
            $this->tag->addAttribute(
                'data-toubiz-static-map.map.google-maps-api-key',
                $apiKeys['googleMaps']
            );
        }

        if (array_key_exists('toursprung', $apiKeys)) {
            $this->tag->addAttribute(
                'data-toubiz-static-map.map.toursprung-api-key',
                $apiKeys['toursprung']
            );
        }
    }
}
