<?php

declare(strict_types=1);

namespace Drupal\simple_interactive_maps\Controller;

use Drupal\Core\Cache\CacheableResponse;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Render\RendererInterface;
use Drupal\simple_interactive_maps\InteractiveMapInterface;
use Drupal\simple_interactive_maps\MapBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Returns responses for Simple Interactive Maps routes.
 */
final class MapThumbnailController extends ControllerBase {

  /**
   * The controller constructor.
   */
  public function __construct(
    protected MapBuilder $mapBuilder,
    protected RendererInterface $renderer,
  ) {}

  /**
   * {@inheritDoc}
   */
  public static function create(ContainerInterface $container): self {
    /** @var \Drupal\simple_interactive_maps\MapBuilder $mapBuilder */
    $mapBuilder = $container->get('simple_interactive_maps.map_builder');

    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = $container->get('renderer');

    return new MapThumbnailController(
      $mapBuilder,
      $renderer
    );
  }

  /**
   * Builds the response.
   */
  public function __invoke(?InteractiveMapInterface $interactive_map = NULL): CacheableResponse {
    $mapRenderData = $this->mapBuilder->getRenderHelper($interactive_map, 'thumbnail');

    // Render the SVG to a string.
    $renderArray = $mapRenderData->getRenderArray();
    $string = (string) $this->renderer->renderInIsolation($renderArray);
    $response = new CacheableResponse($string, 200);
    $response->addCacheableDependency($interactive_map);
    $response->headers->set('Content-Type', 'image/svg+xml');

    return $response;
  }

}
