<?php

namespace Drupal\rufi_structure;

use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\taxonomy\Entity\Term;
use Drupal\taxonomy\TermInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Class PatchBreadcrumbBuilder.
 */
class RuFiStructureTermBreadcrumbBuilder implements BreadcrumbBuilderInterface {
  use StringTranslationTrait;

  /**
   * The current request.
   *
   * @var \Symfony\Component\HttpFoundation\Request|null
   */
  protected ?Request $request;

  /**
   * Constructs the TermBreadcrumbBuilder.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   The entity type manager.
   */
  public function __construct(RequestStack $request_stack) {
    $this->request = $request_stack->getCurrentRequest();
  }

  protected array $routesApply = [
    'entity.taxonomy_term.canonical',
  ];

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    if (in_array($route_match->getRouteName(), $this->routesApply)) {
      /** @var TermInterface $term */
      $term = $route_match->getParameter('taxonomy_term');
      return $term instanceof TermInterface;
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function build(RouteMatchInterface $route_match): Breadcrumb
  {

    $breadcrumb = new Breadcrumb();
    $breadcrumb->addCacheContexts(['route', 'url.query_args']);
    $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));

    /** @var Term $term */
    $term = $route_match->getParameter('taxonomy_term');
    if ($term instanceof TermInterface) {
      $links = [];
      $ref_terms = ($term->parent) ? $term->parent->referencedEntities() : [];
      while ($term = reset($ref_terms)) {
        if (($parent_link = $term->toLink()) && $parent_link instanceof Link) {
          array_unshift($links, $parent_link);
        }
        $ref_terms = ($term->parent) ? $term->parent->referencedEntities() : [];;
      }
      $query = [];
      $base_text = '';
      if ($node_type = $this->request->get('node_type')) {
        $query['node_type'] = $node_type;
        if ($node_type == 'rule') {
          $base_text = $this->t('Rules');
        } elseif ($node_type == 'problem') {
          $base_text = $this->t('Problems');
        }
      }
      if ($ratified = $this->request->get('ratified')) {
        $query['ratified'] = $ratified;
        $base_text = $this->t('Preview');
      }
      if (count($query)) {
        $links[] = Link::createFromRoute($base_text, 'view.rufi_section_tree.section_page');
      }
      foreach (array_reverse($links) as $link) {
        $link->getUrl()->setOption('query', $query);
        $breadcrumb->addLink($link);
      }
    }

    return $breadcrumb;
  }

}
