<?php

declare(strict_types=1);

namespace Drupal\flowdrop\Service;

use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\flowdrop\Attribute\ExpressionEvaluator;
use Drupal\flowdrop\Plugin\ExpressionEvaluator\ExpressionEvaluatorInterface;

/**
 * Plugin manager for ExpressionEvaluator plugins.
 *
 * Discovers and manages expression evaluator implementations that provide
 * different expression syntaxes (PropertyPath, JSONPath, ExpressionLanguage,
 * Twig) for use by data transformation node processors.
 *
 * @see \Drupal\flowdrop\Attribute\ExpressionEvaluator
 * @see \Drupal\flowdrop\Plugin\ExpressionEvaluator\ExpressionEvaluatorInterface
 *
 * @api
 */
class ExpressionEvaluatorPluginManager extends DefaultPluginManager {

  /**
   * Constructs an ExpressionEvaluatorPluginManager 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.
   */
  public function __construct(
    \Traversable $namespaces,
    CacheBackendInterface $cache_backend,
    ModuleHandlerInterface $module_handler,
  ) {
    parent::__construct(
      'Plugin/ExpressionEvaluator',
      $namespaces,
      $module_handler,
      ExpressionEvaluatorInterface::class,
      ExpressionEvaluator::class
    );
    $this->setCacheBackend($cache_backend, 'flowdrop_expression_evaluator_plugins');
    $this->alterInfo('flowdrop_expression_evaluator_info');
  }

  /**
   * Get available evaluator options for use in parameter schema enums.
   *
   * @return array<string, string>
   *   Associative array of plugin ID => label.
   */
  public function getEvaluatorOptions(): array {
    $options = [];
    foreach ($this->getDefinitions() as $id => $definition) {
      $options[$id] = (string) $definition["label"];
    }
    return $options;
  }

}
