<?php

declare(strict_types=1);

namespace Drupal\simple_interactive_maps\Controller;

use Drupal\simple_interactive_maps\InteractiveMapInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Yaml\Yaml;

/**
 * Download the state data as a CSV file.
 */
final class RegionExportController extends DataExportControllerBase {

  /**
   * Builds the response.
   */
  public function __invoke(?InteractiveMapInterface $interactive_map = NULL): BinaryFileResponse {
    if (!($interactive_map instanceof InteractiveMapInterface)) {
      throw new HttpException(404, 'Interactive map not found');
    }

    $regions = $interactive_map->getRegions();

    $headers = [
      'id',
      'label',
      'hidden',
      'group',
      'fill_color',
      'hover_color',
      'stroke_color',
      'text_color',
      'tooltip_value',
      'tooltip_format',
      'action_plugin',
      'action_configuration',
    ];

    $data = [];

    foreach ($regions as $region) {
      $pluginConfig = Yaml::dump($region['action']['plugin_configuration'], 4, 4);

      $data[] = [
        $region['id'],
        $region['label'],
        (int) $region['hidden'],
        $region['group'],
        $region['fill_color'],
        $region['hover_color'],
        $region['stroke_color'],
        $region['text_color'],
        $region['tooltip']['value'],
        $region['tooltip']['format'],
        $region['action']['plugin_id'],
        $pluginConfig,
      ];
      // Export state.
    }

    $fileName = $interactive_map->id() . '_regions.csv';

    return $this->exportCsvFile($data, $headers, $fileName);
  }

}
