<?php

/**
 * @file
 * Contains wxt_ext_editor.module.
 */

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_editor_js_settings_alter().
 */
function wxt_ext_editor_editor_js_settings_alter(array &$settings) {
  foreach ($settings['editor']['formats'] as &$format) {
    // Add a small ckeditor faux plugin.
    if (isset($format['editor']) && $format['editor'] == 'ckeditor') {
      $format['editorSettings']['drupalExternalPlugins']['wxt_ext_editor'] = base_path() . \Drupal::service('extension.list.module')->getPath('wxt_ext_editor') . '/js/wxt_ext_editor.js';
      $format['editorSettings']['extraPlugins'] .= ',wxt_ext_editor';
    }

    // Check if the editor is CKEditor 5 and matches the target text format.
    if (isset($format['editor']) && $format['editor'] === 'ckeditor5') {
      // Ensure the 'list' plugin is loaded after 'conjunctionEditing' plugin.
      $plugins = $format['editorSettings']['plugins'];

      $itemsToMove = ['list.List', 'list.ListProperties'];
      _wxt_ext_editor_move_items_to_end($plugins, $itemsToMove);

      $format['editorSettings']['plugins'] = $plugins;
    }
  }
}

/**
 * Implements hook_form_alter().
 */
function wxt_ext_editor_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $moduleHandler = \Drupal::service('module_handler');

  // Add ckeditor5 library to forms that use ckeditor5.
  if ($moduleHandler->moduleExists('ckeditor5')) {
    foreach ($form as $value) {
      if (!is_object($value)) {
        if (!empty($value['widget'][0]['#type']) && $value['widget'][0]['#type'] == 'text_format') {
          $form['#attached']['library'][] = 'wxt_ext_editor/ckeditor5';
          break;
        }
      }
    }
  }
}

/**
 * Custom function to rearrange order of plugins in CKE5.
 */
function _wxt_ext_editor_move_items_to_end(array &$array, array $itemsToMove): void {
  $movedItems = [];

  // Loop through the items to move.
  foreach ($itemsToMove as $item) {
    // Search for the item in the array.
    $key = array_search($item, $array, TRUE);
    if ($key !== FALSE) {
      // Remove the item from the array and store it for later.
      $movedItems[] = $array[$key];
      unset($array[$key]);
    }
  }

  // Append the removed items to the end of the array.
  $array = array_merge($array, $movedItems);
}
