<?php

/**
 * @file
 * This module provides a block that displays a timeline of events.
 */

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;

/**
 * Implements hook_help().
 */
function timeline_block_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the timeline module.
    case 'help.page.timeline_block':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('Provides a custom block functionality for timeline.') . '</p>';
      return $output;

    default:
  }
}

/**
 * Implements hook_theme().
 */
function timeline_block_theme($existing, $type, $theme, $path) {
  return [
    'timeline_block' => [
      'variables' => [
        'timeline_data' => NULL,
        'timeline_settings' => NULL,
        'timeline_header' => NULL,
        'timeline_layout' => NULL,
      ],
    ],
  ];
}

/**
 * Retrieves image IDs from the timeline description.
 *
 * This function processes the timeline data configuration, extracts the
 * description field from each configuration entry, and fetches associated
 * image IDs from the description using
 * the timeline_block_get_timeline_editor_files function.
 *
 * @param string $timeline_data_config
 *   A JSON-encoded string containing the timeline configuration data.
 *
 * @return array
 *   An array of image IDs extracted from the descriptions within
 *   the timeline data.
 */
function timeline_block_get_timeline_description_images($timeline_data_config) {
  // Initialize an empty array to store image IDs.
  $image_ids = [];

  // Check if the provided timeline data configuration is not empty.
  if ($timeline_data_config != '') {
    // Decode the JSON string into an array of configuration data.
    $all_config_data = json_decode($timeline_data_config);

    // Loop through each configuration entry in the decoded data.
    foreach ($all_config_data as $config_data) {
      // Check if the current configuration entry has a description.
      if (isset($config_data->description)) {
        // Retrieve image IDs associated with the description.
        $old_image_ids = timeline_block_get_timeline_editor_files($config_data->description);

        // Merge the retrieved image IDs into the main array.
        $image_ids = array_merge($image_ids, $old_image_ids);
      }
    }
  }

  // Return the array of image IDs found in the timeline descriptions.
  return $image_ids;
}

/**
 * Implements hook_form_alter().
 */
function timeline_block_form_alter(&$form, FormStateInterface $form_state) {
  if ($form['#form_id'] == 'block_delete_form') {

    $block_entity = $form_state->getFormObject()->getEntity();

    // Get block entity.
    if ($block_entity) {

      $block_plugin_id = $block_entity->getPluginId();

      // Check if the plugin id is timeline_block.
      if ($block_plugin_id == 'timeline_block') {

        $settings = $block_entity->get('settings');

        if (isset($settings['timeline_data'])) {
          $timeline_data = $settings['timeline_data'];
          $timeline_header = $settings['timeline_header'];

          $timeline_block_get_timeline_description_images = timeline_block_get_timeline_description_images($timeline_data);
          $old_header_image_ids = timeline_block_get_timeline_editor_files($timeline_header);

          $timeline_block_get_timeline_description_images = array_merge($timeline_block_get_timeline_description_images, $old_header_image_ids);

          $form_state->set('after_ajax_call', json_encode($timeline_block_get_timeline_description_images));

          if (!empty($timeline_block_get_timeline_description_images)) {

            foreach (array_keys($form['actions']) as $action) {
              if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
                $form['actions'][$action]['#submit'][] = 'timeline_block_form_submit';
              }
            }
          }
        }
      }
    }
  }
}

/**
 * Submit handler for the timeline block form.
 *
 * This function processes the form submission and handles any AJAX-related
 * tasks that involve updating or saving author image files. Specifically,
 * it checks for an 'after_ajax_call' value stored in the form state, decodes
 * it from JSON, and then processes the file IDs within the decoded data.
 * For each file ID, the corresponding file is loaded, set as temporary,
 * and saved to ensure it is properly handled within the Drupal file system.
 *
 * @param array $form
 *   The form array structure.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   The form state object that contains the form values and states.
 */
function timeline_block_form_submit($form, FormStateInterface $form_state) {
  $after_ajax_call = $form_state->get('after_ajax_call');
  if ($after_ajax_call != '') {
    $result = json_decode($after_ajax_call);
    if (!empty($result)) {
      foreach ($result as $author_image_id) {
        $file = File::load($author_image_id);
        $file->setTemporary();
        $file->save();
      }
    }
  }
}

/**
 * Retrieves and processes the files used in the timeline editor content.
 *
 * This function extracts the file UUIDs from the provided content and then
 * loads each corresponding file entity. If the file is temporary, it changes
 * the file's status to permanent and saves it. Additionally, the function
 * adds usage tracking for each file to ensure proper management of the
 * file's lifecycle in the system. Finally, it returns an array of new
 * file IDs that have been processed.
 *
 * @param string $content
 *   The content string that contains the file UUIDs.
 *
 * @return array
 *   An array of file IDs that have been processed and marked as permanent.
 */
function timeline_block_get_timeline_editor_files($content) {
  $new_fids = [];
  $uuids = _editor_parse_file_uuids($content);
  foreach ($uuids as $uuid) {
    if ($file = \Drupal::service('entity.repository')->loadEntityByUuid('file', $uuid)) {
      /** @var \Drupal\file\FileInterface $file */
      if ($file->isTemporary()) {
        $file->setPermanent();
        $file->save();
      }
      $new_fids[] = $file->id();
      \Drupal::service('file.usage')->add($file, 'editor', 'file', $file->fid->value);
    }
  }
  return $new_fids;
}
