<?php

/**
 * @file
 * The Social event type module.
 */

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\taxonomy\TermInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function social_event_type_form_node_event_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  social_event_type_widget_alter($form);
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function social_event_type_form_node_event_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  social_event_type_widget_alter($form);
}

/**
 * Function that does some magic to the event type field.
 *
 * @param array $form
 *   Form array.
 */
function social_event_type_widget_alter(array &$form) {
  $config = \Drupal::config('social_event_type.settings');

  // Check if the field is set to mandatory.
  if ($config->get('social_event_type_required') == TRUE) {
    $form['field_event_type']['widget']['#required'] = TRUE;
  }

  // Set the event type label for none.
  if (isset($form['field_event_type']['widget']['#options']['_none'])) {
    // If the field was set to mandatory, remove the _none option.
    if ($config->get('social_event_type_required') == TRUE) {
      unset($form['field_event_type']['widget']['#options']['_none']);
    }
  }

  // Change the widget if more than X.
  if (count($form['field_event_type']['widget']['#options']) >= $config->get('social_event_type_select_changer')) {
    $form['field_event_type']['widget']['#type'] = 'select';
  }
}

/**
 * Preprocess event node.
 *
 * @param array $variables
 *   Array with variables of a node.
 */
function social_event_type_preprocess_node(array &$variables): void {
  /** @var \Drupal\node\NodeInterface $node */
  $node = $variables['node'];

  if ($node->getType() === 'event') {
    /** @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $event_type_field */
    $event_type_field = $node->get('field_event_type');
    $event_types = $event_type_field->referencedEntities();
    $variables['metadata'] = NULL;
    $variables['event_type'] = NULL;
    $event_type = empty($event_types) ? NULL : reset($event_types);
    if ($event_type instanceof TermInterface) {
      $variables['metadata'] = t('in @event', [
        '@event' => $event_type->toLink()
          ->toString(),
      ]);
      // Set event type link.
      $now = strtotime("now");
      $end = strtotime($node->get('field_event_date_end')->getString());
      // 1 are upcoming events.
      // 2 are ones that have started or are finished.
      $datetype = ($now > $end) ? 2 : 1;
      $event_type_url = Url::fromRoute('view.upcoming_events.page_community_events', [
        'field_event_date_value' => $datetype,
        'event_type_id' => $event_type->id(),
      ]);
      $event_type_link = Link::fromTextAndUrl($event_type->label() ?? '', $event_type_url)
        ->toString();
      $variables['event_type'] = $event_type_link;
      if (
        $event_type->hasField('field_event_type_icon') &&
        !$event_type->get('field_event_type_icon')->isEmpty()
      ) {
        $variables['event_type_icon'] = $event_type->get('field_event_type_icon')->getString();
      }
      $variables['#cache']['tags'][] = $event_type->getEntityTypeId() . ':' . $event_type->id();
    }
  }
}

/**
 * Sets dynamic allowed values for the event type icon field.
 */
function social_event_type_allowed_values_function(FieldStorageConfig $definition, ContentEntityInterface $entity = NULL, $cacheable) {
  $theme_path = \Drupal::service('extension.list.theme')->getPath('socialbase');
  $icon_files = \Drupal::service('file_system')->scanDirectory(DRUPAL_ROOT . '/' . $theme_path . '/components/06-libraries/icons/source', '/^icon-.*\.svg$/', ['recurse' => FALSE]);

  $options = [];
  foreach ($icon_files as $file) {
    $options[$file->name] = $file->name;
  }

  return $options;
}

/**
 * Sets the default value for the event type icon field.
 */
function social_event_type_default_value_function(ContentEntityInterface $entity, FieldDefinitionInterface $definition) {
  return [
    ['value' => 'icon-event'],
  ];
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function social_event_type_form_taxonomy_term_event_types_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (!isset($form['field_event_type_icon'])) {
    return;
  }

  $form['#attached']['library'][] = 'social_event_type/admin';

  $default_icon = $form['field_event_type_icon']['widget']['#default_value'][0];

  $form['field_event_type_icon']['preview'] = [
    '#type' => 'inline_template',
    '#template' => '<div class="icon-svg-wrapper" data-href="#' . $default_icon . '"><svg class="selected-svg"><use xlink:href="#' . $default_icon . '"></use></svg>{{ svg_icons|raw }}</div>',
    '#context' => [
      'svg_icons' => file_get_contents(\Drupal::service('extension.list.theme')->getPath('socialbase') . '/assets/icons/icons.svg'),
    ],
  ];

  $form['field_event_type_icon']['widget']['#ajax'] = [
    'callback' => '_social_event_type_change_topic_icon_ajax',
    'event' => 'change',
  ];
}

/**
 * Ajax callback to change event type icon.
 */
function _social_event_type_change_topic_icon_ajax(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();

  $icon = $form_state->getValue('field_event_type_icon')[0]['value'];
  $replaced = [
    '#type' => 'inline_template',
    '#template' => '<div class="icon-svg-wrapper" data-href="#' . $icon . '"><svg class="selected-svg"><use xlink:href="#' . $icon . '"></use></svg>{{ svg_icons|raw }}</div>',
    '#context' => [
      'svg_icons' => file_get_contents(\Drupal::service('extension.list.theme')->getPath('socialbase') . '/assets/icons/icons.svg'),
    ],
  ];

  $response->addCommand(new ReplaceCommand('.icon-svg-wrapper', $replaced));

  return $response;
}
