<?php

namespace Drupal\pagedesigner\Service;

use Drupal\Component\Plugin\FallbackPluginManagerInterface;
use Drupal\Component\Utility\SortArray;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\pagedesigner\Annotation\PagedesignerHandler;
use Drupal\pagedesigner\Plugin\pagedesigner\HandlerPluginInterface;

/**
 * Handler manager for pagedesigner element handlers.
 *
 * @see \Drupal\Core\Archiver\Annotation\Archiver
 * @see \Drupal\Core\Archiver\ArchiverInterface
 * @see plugin_api
 */
class HandlerPluginManager extends DefaultPluginManager implements FallbackPluginManagerInterface {

  /**
   * Constructs a RendererPluginManager 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/pagedesigner/Handler',
          $namespaces,
          $module_handler,
          HandlerPluginInterface::class,
          PagedesignerHandler::class
      );
    $this->alterInfo('pagedesigner_handler_info');
    $this->setCacheBackend($cache_backend, 'pagedesigner_handler_info_plugins');
  }

  /**
   * Overrides PluginManagerBase::getInstance().
   *
   * @param array $options
   *   An array with the following key/value pairs:
   *   - id: The id of the plugin.
   *   - type: The type of the pattern field.
   *
   * @return \Drupal\pagedesigner\Plugin\pagedesigner\HandlerPluginInterface[]
   *   A list of Handler objects.
   */
  public function getInstance(array $options) {
    $handlers = [];
    $definitions = [];
    $type = '*';
    $configuration = [];
    if (!empty($options['entity'])) {
      $type = $options['entity']->bundle();
    }
    else {
      $type = $options['type'];
    }
    $allDefinitions = $this->getDefinitions();
    foreach ($allDefinitions as $plugin_id => $definition) {
      if (in_array($type, $definition['types'])) {
        $definitions[$plugin_id] = $definition;
      }
    }
    if (count($definitions)) {
      uasort($definitions, [SortArray::class, 'sortByWeightElement']);
      foreach ($definitions as $plugin_id => $definition) {
        $handlers[] = $this
          ->createInstance($plugin_id, $configuration);
      }
    }
    if (empty($handlers)) {
      $handlers[] = $this
        ->createInstance($this->getFallbackPluginId($type), $configuration);
    }
    return $handlers;
  }

  /**
   * Returns all handlers.
   *
   * @return \Drupal\pagedesigner\Plugin\pagedesigner\HandlerPluginInterface[]
   *   A list of Handler objects.
   */
  public function getHandlers() {
    $handlers = [];
    $configuration = [];
    foreach ($this->getDefinitions() as $plugin_id => $definition) {
      $handlers[] = $this
        ->createInstance($plugin_id, $configuration);
    }
    return $handlers;
  }

  /**
   * {@inheritdoc}
   */
  public function getFallbackPluginId($plugin_id, array $configuration = []) {
    return 'content';
  }

}
