<?php

declare(strict_types=1);

namespace Drupal\layout_builder_browser_library\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * Ensure we alter the controller after other modules.
   *
   * @see https://www.drupal.org/node/3129158
   */
  public const int WEIGHT = -120;

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection): void {
    // Override the layout builder choose block controller with ours.
    $route = $collection->get('layout_builder.choose_block');
    if ($route) {
      $route->setDefault('_controller', '\Drupal\layout_builder_browser_library\Controller\BrowserController::browse');
    }
  }

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

}
