<?php

namespace Drupal\acquia_contenthub_publisher\Routing;

use Drupal\acquia_contenthub_publisher\Form\AcquiaContentHubExcludeFieldsForm;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 *
 * Creates new routes for the UI of excluding fields
 * from dependency calculation.
 */
class RouteSubscriber extends RouteSubscriberBase {

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

  /**
   * Constructs a new AchRouteSubscriber object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
   *   The entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_manager) {
    $this->entityTypeManager = $entity_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    $events = parent::getSubscribedEvents();
    $events[RoutingEvents::ALTER] = 'onAlterRoutes';
    return $events;
  }

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
      if ($route = $this->getRoute($entity_type, $collection)) {
        $collection->add("entity.$entity_type_id.contenthub_export", $route);
      }
    }
  }

  /**
   * Provides ACH route for excluding fields.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   Entity type.
   * @param \Symfony\Component\Routing\RouteCollection $collection
   *   Route collection.
   *
   * @return \Symfony\Component\Routing\Route|void
   *   Route for the given entity type.
   */
  protected function getRoute(EntityTypeInterface $entity_type, RouteCollection $collection) {
    if ($route_name = $entity_type->get('field_ui_base_route')) {
      // Try to get the route from the current collection.
      if (!$entity_route = $collection->get($route_name)) {
        return;
      }
      $path = $entity_route->getPath();
      $entity_type_id = $entity_type->id();
      $options = $entity_route->getOptions();
      $options['_field_ui'] = TRUE;
      if ($bundle_entity_type = $entity_type->getBundleEntityType()) {
        $options['parameters'][$bundle_entity_type] = [
          'type' => 'entity:' . $bundle_entity_type,
        ];
      }

      $defaults = [
        'entity_type_id' => $entity_type_id,
      ];
      // If the entity type has no bundles and it doesn't use {bundle} in its
      // admin path, use the entity type.
      if (!str_contains($path, '{bundle}')) {
        $defaults['bundle'] = !$entity_type->hasKey('bundle') ? $entity_type_id : '';
      }

      return new Route(
        "$path/contenthub",
        [
          '_form' => AcquiaContentHubExcludeFieldsForm::class,
          '_title' => 'Manage Content Hub export',
        ] + $defaults,
        ['_permission' => 'administer acquia content hub'],
        $options
      );
    }
  }

}
