<?php

declare(strict_types = 1);

namespace Drupal\ckeditor5\Plugin;

use Drupal\ckeditor5\Annotation\CKEditor4To5Upgrade;
use Drupal\ckeditor5\HTMLRestrictions;
use Drupal\Component\Assertion\Inspector;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\filter\FilterFormatInterface;

/**
 * Provides a CKEditor 4 to 5 upgrade plugin manager.
 *
 * @see \Drupal\ckeditor5\Plugin\CKEditor4To5UpgradePluginInterface
 * @see \Drupal\ckeditor5\Annotation\CKEditor4To5Upgrade
 * @see plugin_api
 *
 * @internal
 */
class CKEditor4To5UpgradePluginManager extends DefaultPluginManager {

  /**
   * A map of CKEditor 4 buttons to an upgrade plugin ID.
   *
   * @var array
   */
  protected $cke4ButtonsMap;

  /**
   * A map of CKEditor 4 plugins with settings to an upgrade plugin ID.
   *
   * @var array
   */
  protected $cke4PluginSettingsMap;

  /**
   * A map of CKEditor 5 plugins with configurable subset to upgrade plugin ID.
   *
   * @var array
   */
  protected $cke5SubsetConfigurationMap;

  /**
   * Constructs a CKEditor4To5UpgradePluginManager object.
   *
   * @param \Traversable $namespaces
   *   An object that implements \Traversable which contains the root paths
   *   keyed by the corresponding namespace to look for plugin implementations.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   Cache backend instance to use.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler to invoke the alter hook with.
   */
  public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {
    parent::__construct('Plugin/CKEditor4To5Upgrade', $namespaces, $module_handler, CKEditor4To5UpgradePluginInterface::class, CKEditor4To5Upgrade::class);

    $this->alterInfo('ckeditor4to5upgrade_plugin_info');
    $this->setCacheBackend($cache_backend, 'ckeditor4to5upgrade_plugins');
  }

  /**
   * Validates plugin definitions: avoids conflicts. Builds maps for later use.
   */
  protected function validateAndBuildMaps(): void {
    if ($this->cke4ButtonsMap !== NULL) {
      return;
    }

    foreach ($this->getDefinitions() as $upgrade_plugin_id => $definition) {
      // Only one CKEditor4To5Upgrade plugin can define the upgrade path for a
      // CKEditor 4 button.
      if (isset($definition['cke4_buttons'])) {
        assert(Inspector::assertAllStrings($definition['cke4_buttons']));
        foreach ($definition['cke4_buttons'] as $cke4_button_id) {
          if (isset($this->cke4ButtonsMap[$cke4_button_id])) {
            throw new \OutOfBoundsException(sprintf('The "%s" CKEditor 4 button is already being upgraded by the "%s" CKEditor4To5Upgrade plugin, the "%s" plugin is as well. This conflict needs to be resolved.', $cke4_button_id, $this->cke4ButtonsMap[$cke4_button_id], $upgrade_plugin_id));
          }
          $this->cke4ButtonsMap[$cke4_button_id] = $upgrade_plugin_id;
        }
      }

      // Only one CKEditor4To5Upgrade plugin can define the upgrade path for a
      // CKEditor 4 plugin's settings.
      if (isset($definition['cke4_plugin_settings'])) {
        assert(Inspector::assertAllStrings($definition['cke4_plugin_settings']));
        foreach ($definition['cke4_plugin_settings'] as $cke4_plugin_id) {
          if (isset($this->cke4PluginSettingsMap[$cke4_plugin_id])) {
            throw new \OutOfBoundsException(sprintf('The "%s" CKEditor 4 plugin\'s settings are already being upgraded by the "%s" CKEditor4To5Upgrade plugin, the "%s" plugin is as well. This conflict needs to be resolved.', $cke4_plugin_id, $this->cke4PluginSettingsMap[$cke4_plugin_id], $upgrade_plugin_id));
          }
          $this->cke4PluginSettingsMap[$cke4_plugin_id] = $upgrade_plugin_id;
        }
      }

      // Only one CKEditor4To5Upgrade plugin can define the upgrade path for a
      // CKEditor 5 plugin's elements subset configuration.
      if (isset($definition['cke5_plugin_elements_subset_configuration'])) {
        assert(Inspector::assertAllStrings($definition['cke5_plugin_elements_subset_configuration']));
        foreach ($definition['cke5_plugin_elements_subset_configuration'] as $cke5_plugin_id) {
          if (isset($this->cke5SubsetConfigurationMap[$cke5_plugin_id])) {
            throw new \OutOfBoundsException(sprintf('The "%s" CKEditor 5 plugin\'s elements subset configuration is already being computed by the "%s" CKEditor4To5Upgrade plugin, the "%s" plugin is as well. This conflict needs to be resolved.', $cke5_plugin_id, $this->cke5SubsetConfigurationMap[$cke5_plugin_id], $upgrade_plugin_id));
          }
          $this->cke5SubsetConfigurationMap[$cke5_plugin_id] = $upgrade_plugin_id;
        }
      }
    }
  }

  /**
   * Maps a CKEditor 4 button to the CKEditor 5 equivalent, if it exists.
   *
   * Generated by inspecting all \Drupal\ckeditor\CKEditorPluginButtonsInterface
   * implementations.
   *
   * @param string $cke4_button
   *   A valid CKEditor 4 button name.
   * @param \Drupal\ckeditor5\HTMLRestrictions $text_format_html_restrictions
   *   The restrictions of the text format, to allow an upgrade plugin to
   *   inspect the text format's HTML restrictions to make a decision.
   *
   * @return string[]|null
   *   The equivalent CKEditor 5 toolbar items, or NULL if no equivalent exists.
   *
   * @throws \OutOfBoundsException
   *   Thrown when no upgrade path exists.
   * @throws \LogicException
   *   Thrown when a plugin claims to provide an upgrade path but does not.
   *
   * @see \Drupal\ckeditor\CKEditorPluginButtonsInterface
   */
  public function mapCKEditor4ToolbarButtonToCKEditor5ToolbarItem(string $cke4_button, HTMLRestrictions $text_format_html_restrictions): ?array {
    $this->validateAndBuildMaps();

    if (!isset($this->cke4ButtonsMap[$cke4_button])) {
      throw new \OutOfBoundsException(sprintf('No upgrade path found for the "%s" button.', $cke4_button));
    }

    $plugin_id = $this->cke4ButtonsMap[$cke4_button];
    try {
      return $this->createInstance($plugin_id)->mapCKEditor4ToolbarButtonToCKEditor5ToolbarItem($cke4_button, $text_format_html_restrictions);
    }
    catch (\OutOfBoundsException $e) {
      throw new \LogicException(sprintf('The "%s" CKEditor4To5Upgrade plugin claims to provide an upgrade path for the "%s" CKEditor 4 button but does not.', $plugin_id, $cke4_button));
    }
  }

  /**
   * Maps CKEditor 4 settings to the CKEditor 5 equivalent, if needed.
   *
   * Not every CKEditor 5 plugin has settings; some CKEditor 5 plugins may have
   * settings that the CKEditor 4 equivalent did not and vice versa. Therefore
   * the complete CKEditor 4 settings are provided, and any CKEditor 5 setting
   * can be set.
   *
   * @param string $cke4_plugin_id
   *   The CKEditor 4 plugin whose settings need to be mapped.
   * @param array $cke4_plugin_settings
   *   The settings for this CKEditor 4 plugin.
   *
   * @return array|null
   *   NULL if not needed, otherwise an array with a single key-value pair:
   *   - key: the plugin ID of the equivalent CKEditor 5 plugin
   *   - value: the equivalent settings
   *
   * @throws \OutOfBoundsException
   *   Thrown when no upgrade path exists.
   * @throws \LogicException
   *   Thrown when a plugin claims to provide an upgrade path but does not.
   *
   * @see \Drupal\ckeditor\CKEditorPluginConfigurableInterface
   */
  public function mapCKEditor4SettingsToCKEditor5Configuration(string $cke4_plugin_id, array $cke4_plugin_settings): ?array {
    $this->validateAndBuildMaps();

    if (!isset($this->cke4PluginSettingsMap[$cke4_plugin_id])) {
      throw new \OutOfBoundsException(sprintf('No upgrade path found for the "%s" plugin settings.', $cke4_plugin_id));
    }

    $plugin_id = $this->cke4PluginSettingsMap[$cke4_plugin_id];
    try {
      return $this->createInstance($plugin_id)->mapCKEditor4SettingsToCKEditor5Configuration($cke4_plugin_id, $cke4_plugin_settings);
    }
    catch (\OutOfBoundsException $e) {
      throw new \LogicException(sprintf('The "%s" CKEditor4To5Upgrade plugin claims to provide an upgrade path for the "%s" CKEditor 4 plugin settings but does not.', $plugin_id, $cke4_plugin_id));
    }
  }

  /**
   * Computes elements subset configuration for CKEditor 5 plugin.
   *
   * Every CKEditor 5 plugin that implements the elements subset interface must
   * implement this as well, to ensure a smooth upgrade path.
   *
   * @param string $cke5_plugin_id
   *   The CKEditor 5 plugin whose subset configuration needs to be computed.
   * @param \Drupal\filter\FilterFormatInterface $text_format
   *   The text format based on whose restrictions this should be computed.
   *
   * @return array|null
   *   NULL if not needed, otherwise a configuration array (which can itself be
   *   a subset of the default configuration of this CKEditor 5 plugin: perhaps
   *   only some of the configuration values determine the subset).
   *
   * @throws \OutOfBoundsException
   *   Thrown when no upgrade path exists.
   * @throws \LogicException
   *   Thrown when a plugin claims to provide an upgrade path but does not.
   *
   * @see \Drupal\ckeditor5\Plugin\CKEditor5PluginElementsSubsetInterface
   */
  public function computeCKEditor5PluginSubsetConfiguration(string $cke5_plugin_id, FilterFormatInterface $text_format): ?array {
    $this->validateAndBuildMaps();

    if (!isset($this->cke5SubsetConfigurationMap[$cke5_plugin_id])) {
      throw new \OutOfBoundsException(sprintf('No upgrade path found for the "%s" elements subset configuration.', $cke5_plugin_id));
    }

    $plugin_id = $this->cke5SubsetConfigurationMap[$cke5_plugin_id];
    try {
      return $this->createInstance($plugin_id)->computeCKEditor5PluginSubsetConfiguration($cke5_plugin_id, $text_format);
    }
    catch (\OutOfBoundsException $e) {
      throw new \LogicException(sprintf('The "%s" CKEditor4To5Upgrade plugin claims to provide an upgrade path for the "%s" CKEditor 4 plugin settings but does not.', $plugin_id, $cke5_plugin_id));
    }
  }

}
