<?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 group data as a CSV file.
 */
final class GroupExportController 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');
    }

    $groups = $interactive_map->get('groups');

    $header = [
      'id',
      'label',
      'override_colors',
      'fill_color',
      'hover_color',
      'stroke_color',
      'text_color',
      'override_tooltip',
      'tooltip_value',
      'tooltip_format',
      'override_action',
      'action_plugin',
      'action_configuration',
    ];

    $data = [];

    foreach ($groups as $id => $group) {
      $pluginConfig = Yaml::dump($group['action']['plugin_configuration'], 4, 4);

      $data[] = [
        $id,
        $group['label'],
        $group['override_colors'],
        $group['fill_color'],
        $group['hover_color'],
        $group['stroke_color'],
        $group['text_color'],
        $group['override_tooltip'],
        $group['tooltip']['value'],
        $group['tooltip']['format'],
        $group['override_action'],
        $group['action']['plugin_id'],
        $pluginConfig,
      ];
    }

    $filename = $interactive_map->id() . '_groups.csv';

    return $this->exportCsvFile($data, $header, $filename);
  }

}
