<?php

namespace Drupal\component_builder;

use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Link;
use Drupal\Core\Render\Markup;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
 * Class to define the bath breadcrumb builder.
 */
class ComponentBreadcrumb implements BreadcrumbBuilderInterface {

  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    return preg_match('/^entity.([^#]+).canonical$/', $route_match->getRouteName()) === 1 ? TRUE : FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function build(RouteMatchInterface $route_match) {
    $breadcrumb = new Breadcrumb();
    $breadcrumb->addCacheContexts(['route']);
    $parts = explode('.', $route_match->getRouteName());
    $entity_type = $parts[1];
    $updated = FALSE;
    /** @var \Drupal\component_builder\ComponentBuilderHelper $componentBuilderHelper */
    $componentBuilderHelper = \Drupal::service('component_builder.helper');
    $referenced_entities = $componentBuilderHelper->getFieldsReferencedComponent($entity_type);
    if ($referenced_entities && $route_match->getParameters()->has($entity_type)) {
      /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
      $entity = $route_match->getParameter($entity_type);
      $entity_bundle = $entity->bundle();
      $field_storage = $referenced_entities[$entity_bundle];
      foreach ($field_storage as $field_name => $value) {
        $field_component_wrapper = $entity->get($field_name);
        $field_component_wrappers = $field_component_wrapper->referencedEntities();
        if ($field_component_wrappers) {
          foreach ($field_component_wrappers as $field_component_wrapper) {
            if ($field_component_wrapper->hasField('field_breadcrumb')) {
              $field_breadcrumbs = $field_component_wrapper->get('field_breadcrumb')->referencedEntities();
              if ($field_breadcrumbs) {
                foreach ($field_breadcrumbs as $field_breadcrumb) {
                  $field_breadcrumb_link = $field_breadcrumb->get('field_breadcrumb_link');
                  $field_breadcrumb_link = reset($field_breadcrumb_link);
                  if ($field_breadcrumb_link) {
                    foreach ($field_breadcrumb_link as $link_item) {
                      $title = Markup::create($field_breadcrumb->getTitle());
                      $url = $link_item->getUrl();
                      $link = Link::fromTextAndUrl($title, $url);
                      $breadcrumb->addLink($link);
                    }
                  }
                }
                $updated = TRUE;
                break;
              }
            }
          }
        }
        if ($updated) {
          break;
        }
      }

      $breadcrumb->addCacheTags(Cache::mergeTags([$entity_type . ':' . $entity->id()]));
    }

    return $breadcrumb;
  }

}
