<?php

declare(strict_types=1);

namespace Drupal\simple_interactive_maps\Form;

use Drupal\Component\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;
use Drupal\simple_interactive_maps\InteractiveMapInterface;
use Symfony\Component\HttpKernel\Exception\HttpException;

/**
 * Group data upload form.
 */
final class GroupDataImportForm extends DataImportFormBase {

  /**
   * {@inheritDoc}
   */
  public function getFormId(): string {
    return 'simple_interactive_maps_group_data_import';
  }

  /**
   * {@inheritDoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, ?InteractiveMapInterface $interactive_map = NULL): array {
    if (!($interactive_map instanceof InteractiveMapInterface)) {
      throw new HttpException(404, 'Interactive map not found');
    }

    $form['map'] = [
      '#type' => 'value',
      '#value' => $interactive_map,
    ];

    $form['import_group_file'] = [
      '#type' => 'file',
      '#title' => $this->t('Import groups'),
      '#element_validate' => ['::validateFileUpload'],
      '#required' => FALSE,
      '#description' => $this->t('Upload a CSV file with group data.'),
    ];

    $form['actions'] = [
      '#type' => 'actions',
      'submit' => [
        '#type' => 'submit',
        '#value' => $this->t('Send'),
      ],
    ];

    return $form;
  }

  /**
   * {@inheritDoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $fieldId = $this->getUploadFieldId();

    $file = $form_state->getValue($fieldId);
    $file_path = $file->getFileUri();
    $fh = fopen($file_path, 'rb');
    // Get headers and dispose of them.
    fgetcsv($fh);
    $groups = [];
    while ($row = fgetcsv($fh)) {
      $group = [
        'id' => $row[0],
        'label' => $row[1],
        'override_colors' => (bool) $row[2],
        'fill_color' => $row[3],
        'hover_color' => $row[4],
        'stroke_color' => $row[5],
        'text_color' => $row[6],
        'override_tooltip' => (bool) $row[7],
        'tooltip' => [
          'value' => $row[8],
          'format' => $row[9],
        ],
        'override_action' => (bool) $row[10],
        'action' => [
          'plugin_id' => $row[11],
          'plugin_configuration' => Yaml::decode($row[12]),
        ],
      ];
      $groups[$row[0]] = $group;
    }
    fclose($fh);

    $interactiveMap = $form_state->getValue('map');
    $interactiveMap->set('groups', $groups);
    $interactiveMap->save();

    $this->messenger()->addStatus($this->t('Group data has been imported.'));

    $form_state->setRedirect('simple_interactive_maps.simple_interactive_maps_tools', ['interactive_map' => $interactiveMap->id()]);
  }

  /**
   * {@inheritDoc}
   */
  protected function getUploadFieldId(): string {
    return 'import_group_file';
  }

}
