<?php

namespace Drupal\straker_translate\FieldProcessor;

use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;

/**
 * Provides a StrakerTranslateFieldProcessor plugin manager.
 *
 * @see \Drupal\straker_translate\RelatedEntitiesDetector
 * @see plugin_api
 */
class StrakerTranslateFieldProcessorManager extends DefaultPluginManager {

  /**
   * Constructs a new StrakerTranslateFieldProcessorManager 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/StrakerTranslateFieldProcessor',
      $namespaces,
      $module_handler,
      'Drupal\straker_translate\FieldProcessor\StrakerTranslateFieldProcessorInterface',
      'Drupal\straker_translate\Annotation\StrakerTranslateFieldProcessor'
    );
    $this->alterInfo('straker_translate_field_processor_info');
    $this->setCacheBackend($cache_backend, 'straker_translate_field_processor_info_plugins');
  }

  /**
   *
   */
  public function getProcessorsForField($field_definition, $entity) {
    $field_processor_definitions = $this->getDefinitions();
    $valid_processors = [];
    uasort($field_processor_definitions, 'Drupal\Component\Utility\SortArray::sortByWeightElement');
    foreach ($field_processor_definitions as $field_processor_definition_id => $field_processor_definition) {
      /** @var \Drupal\straker_translate\FieldProcessor\StrakerTranslateFieldProcessorInterface $processor */
      $processor = $this->createInstance($field_processor_definition_id, []);
      if ($processor->appliesToField($field_definition, $entity)) {
        $valid_processors[] = $processor;
      }
    }
    if (empty($valid_processors)) {
      $valid_processors[] = $this->getDefaultProcessor();
    }
    // @todo Decide if the first applying processor should exclude others, or if we should allow to refine extractions.
    return $valid_processors;
  }

  /**
   *
   */
  public function getDefaultProcessor() {
    return $this->createInstance('default');
  }

}
