<?php

declare(strict_types=1);

namespace Drupal\simple_interactive_maps\EventSubscriber;

use Drupal\Core\Url;
use Drupal\simple_interactive_maps\Event\MapBuildEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Event subscriber for the map build event.
 */
final class MapBuildEventSubscriber implements EventSubscriberInterface {

  /**
   * Event callback for the map build event.
   *
   * @param \Drupal\simple_interactive_maps\Event\MapBuildEvent $event
   *   The map build event.
   */
  public function onMapBuild(MapBuildEvent $event): void {
    if ($event->getContext() == 'thumbnail') {
      $renderHelper = $event->getRenderData();
      $svg = $renderHelper->getRenderArray();
      $svg['#attributes']['height'] = 300;
      $renderHelper->setRenderArray($svg);
      $event->setRenderData($renderHelper);
    }

    if ($event->getContext() === 'region_editor') {
      $renderHelper = $event->getRenderData();

      $settings = $renderHelper->getSettings();

      foreach ($settings as $region => $config) {
        $settings[$region]['action']['name'] = 'navigate_action';
        $config = [
          'new_tab' => FALSE,
          'url' => Url::fromRoute('simple_interactive_maps.region_edit', [
            'interactive_map' => $event->getMap()->id(),
            'region_id' => $region,
          ],
            [
              'query' => [
                'destination' => Url::fromRoute('<current>')->toString(),
              ],
            ]
          )->toString(TRUE)->getGeneratedUrl(),
        ];
        $settings[$region]['action']['configuration'] = $config;
      }

      $renderHelper->setSettings($settings);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    return [
      MapBuildEvent::EVENT_NAME => 'onMapBuild',
    ];
  }

}
