<?php

declare(strict_types=1);

namespace Drupal\sobki_theme_bootstrap\HookHandler;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Controller\TitleResolverInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Routing\CurrentRouteMatch;
use Drupal\Core\Template\Attribute;
use Drupal\ui_patterns\Plugin\UiPatterns\PropType\LinksPropType;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Append current page title.
 */
class PreprocessBreadcrumb implements ContainerInjectionInterface {

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected RequestStack $requestStack;

  /**
   * The current route match.
   *
   * @var \Drupal\Core\Routing\CurrentRouteMatch
   */
  protected CurrentRouteMatch $currentRouteMatch;

  /**
   * The title resolver.
   *
   * @var \Drupal\Core\Controller\TitleResolverInterface
   */
  protected TitleResolverInterface $titleResolver;

  /**
   * Constructor.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
   *   The request stack.
   * @param \Drupal\Core\Routing\CurrentRouteMatch $currentRouteMatch
   *   The current route match.
   * @param \Drupal\Core\Controller\TitleResolverInterface $titleResolver
   *   The title resolver.
   */
  public function __construct(
    RequestStack $requestStack,
    CurrentRouteMatch $currentRouteMatch,
    TitleResolverInterface $titleResolver,
  ) {
    $this->requestStack = $requestStack;
    $this->currentRouteMatch = $currentRouteMatch;
    $this->titleResolver = $titleResolver;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): self {
    return new self(
      $container->get('request_stack'),
      $container->get('current_route_match'),
      $container->get('title_resolver'),
    );
  }

  /**
   * Append current page title.
   *
   * @param array $variables
   *   The preprocessed variables.
   */
  public function preprocess(array &$variables): void {
    $request = $this->requestStack->getCurrentRequest();
    if ($request == NULL) {
      return;
    }

    $route = $this->currentRouteMatch->getRouteObject();
    if ($route == NULL) {
      return;
    }

    $page_title = $this->titleResolver->getTitle($request, $route);
    if (!empty($page_title)) {
      $variables['breadcrumb'][] = [
        'text' => $page_title,
        'attributes' => new Attribute(['class' => ['active']]),
      ];
      $variables['breadcrumb'] = LinksPropType::normalize($variables['breadcrumb']);
    }

    // Add cache context based on url.
    $cache = new CacheableMetadata();
    $cache->addCacheContexts([
      'route',
      'url.path',
      'languages',
    ]);
    $cache->applyTo($variables);
  }

}
