<?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\InteractiveMapFormTempStoreTrait;
use Drupal\simple_interactive_maps\InteractiveMapInterface;
use Drupal\simple_interactive_maps\MapDataLoader;
use Symfony\Component\HttpKernel\Exception\HttpException;

/**
 * Region data upload form.
 */
final class RegionDataImportForm extends DataImportFormBase {

  use InteractiveMapFormTempStoreTrait;

  /**
   * {@inheritDoc}
   */
  public function getFormId(): string {
    return 'simple_interactive_maps_region_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_regions_file'] = [
      '#type' => 'file',
      '#title' => $this->t('Import regions'),
      '#element_validate' => ['::validateFileUpload'],
      '#required' => FALSE,
      '#description' => $this->t('Upload a CSV file with region 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, 'r');
    // Get headers and dispose of them.
    fgetcsv($fh);
    $regions = [];
    while ($row = fgetcsv($fh)) {
      $region = [
        'id' => $row[0],
        'label' => $row[1],
        'hidden' => $this->truthifyValue($row[2]) ? 1 : 0,
        'group' => $row[3],
        'fill_color' => $row[4],
        'hover_color' => $row[5],
        'stroke_color' => $row[6],
        'text_color' => $row[7],
        'tooltip' => [
          'value' => $row[8],
          'format' => $row[9],
        ],
        'action' => [
          'plugin_id' => $row[10],
          'plugin_configuration' => Yaml::decode($row[11]),
        ],
      ];
      $regions[$row[0]] = $region;
    }
    fclose($fh);

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

    $regionTempStorage = $this->getMapTempStore($interactiveMap);
    $regionTempStorage->delete(MapDataLoader::MAP_TEMP_STORE_REGIONS_KEY);

    $this->messenger()->addStatus($this->t('Region 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_regions_file';
  }

  /**
   * Check the incoming value and try to intelligently convert to a boolean.
   *
   * @param string $value
   *   Value to convert.
   *
   * @return bool
   *   Truth value.
   */
  public function truthifyValue($value): bool {
    return match($value) {
      '1', 'true', 'TRUE', 'True', 'yes', 'YES', 'Yes' => TRUE,
      default => FALSE,
    };
  }

}
