<?php

namespace Drupal\component_builder_toolbar\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\component_builder\ComponentBuilderHelperInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides derivative plugins for the ComponentBuilderToolbarLocalTasks plugin.
 */
class ComponentBuilderToolbarLocalTasks extends DeriverBase implements ContainerDeriverInterface {

  use StringTranslationTrait;

  /**
   * The base plugin ID.
   *
   * @var string
   */
  protected $basePluginId;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The component builder helper service.
   *
   * @var \Drupal\component_builder\ComponentBuilderHelperInterface
   */
  protected $componentBuilderHelper;

  /**
   * Constructs a new ComponentBuilderToolbarLocalTasks object.
   *
   * @param string $base_plugin_id
   *   The base plugin ID.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\component_builder\ComponentBuilderHelperInterface $component_builder_helper
   *   The component builder helper service.
   */
  public function __construct($base_plugin_id, EntityTypeManagerInterface $entity_type_manager, ComponentBuilderHelperInterface $component_builder_helper) {
    $this->basePluginId = $base_plugin_id;
    $this->entityTypeManager = $entity_type_manager;
    $this->componentBuilderHelper = $component_builder_helper;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, $base_plugin_id) {
    return new static(
      $base_plugin_id,
      $container->get('entity_type.manager'),
      $container->get('component_builder.helper')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getDerivativeDefinitions($base_plugin_definition) {

    $referenced_entities = $this->componentBuilderHelper->getFieldsReferencedComponent();
    foreach ($referenced_entities as $entity_type_id => $entity_info) {
      $component_builder_toolbar_route_name = "entity.{$entity_type_id}.component_builder_toolbar";
      $base_route_name = "entity.$entity_type_id.canonical";

      $this->derivatives[$component_builder_toolbar_route_name] = [
        'entity_type' => $entity_type_id,
        'title' => $this->t('Builder'),
        'route_name' => $component_builder_toolbar_route_name,
        'base_route' => $base_route_name,
        'weight' => 999,
      ] + $base_plugin_definition;
    }
    return parent::getDerivativeDefinitions($base_plugin_definition);
  }

}
