<?php

/**
 * @file
 * Provides extra menu links for the core drupal toolbar.
 */

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Cache\CacheableMetadata;

/**
 * Implements hook_toolbar().
 */
function admin_toolbar_tools_toolbar() {
  $items = [];
  $items['admin_toolbar_tools'] = [
    '#type' => 'toolbar_item',
    'tab' => [
      '#type' => 'link',
      '#attributes' => [
        'class' => ['toolbar-icon', 'toolbar-icon-admin-toolbar-tools-help'],
      ],
    ],
    '#attached' => ['library' => ['admin_toolbar_tools/toolbar.icon']],
  ];

  // Toolbar item for primary local tasks.
  $config_object = \Drupal::config('admin_toolbar_tools.settings');
  $config = $config_object->get('show_local_tasks');
  $items['admin_toolbar_local_tasks'] = [];
  CacheableMetadata::createFromObject($config_object)->applyTo($items['admin_toolbar_local_tasks']);

  if ($config) {
    $items['admin_toolbar_local_tasks'] += [
      '#type' => 'toolbar_item',
      '#wrapper_attributes' => [
        'class' => ['local-tasks-toolbar-tab'],
      ],
      // Put it after contextual toolbar item so when float right is applied
      // local tasks item will be first.
      '#weight' => 10,
      'tab' => [
        // We can't use #lazy_builder here because
        // ToolbarItem::preRenderToolbarItem will insert #attributes before
        // lazy_builder callback and this will produce Exception.
        // This means that for now we always render Local Tasks item even when
        // the tray is empty.
        '#type' => 'link',
        '#title' => t('Local Tasks'),
        '#url' => Url::fromRoute('<none>'),
        '#attributes' => [
          'class' => [
            'toolbar-icon',
            'toolbar-icon-local-tasks',
          ],
        ],
      ],
      'tray' => [
        'local_links' => [
          '#lazy_builder' => [
            'admin_toolbar_tools.helper:localTasksTrayLazyBuilder',
            [],
          ],
        ],
      ],
      '#attached' => ['library' => ['admin_toolbar_tools/toolbar.icon']],
    ];
  }

  return $items;
}

/**
 * Implements hook_preprocess_html().
 */
function admin_toolbar_tools_preprocess_html(&$variables) {
  if (\Drupal::currentUser()->hasPermission('access toolbar')) {
    $variables['attributes']['class'][] = 'toolbar-icon-' . intval(\Drupal::VERSION);
  }
}

/**
 * Implements hook_help().
 */
function admin_toolbar_tools_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.admin_toolbar_tools':
      $output = '';
      $output .= '<p>';
      $output .= t('The Admin Toolbar Extra Tools module comes packaged with the <a href=":admin-toolbar">Admin Toolbar</a> module and adds functionality to it. The additional functionality is accessed through extra links on the main administration Toolbar. Some links to Admin Toolbar Extra Tools administration pages are located at the bottom of this page.</a>', [':admin-toolbar' => Url::fromRoute('help.page', ['name' => 'admin_toolbar'])->toString()]);
      $output .= '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<p>' . t('To use Admin Toolbar Extra Tools just install it like any other module. There is no other configuration required.') . '</p>';
      return $output;
  }
}

/**
 * Implements hook_entity_insert().
 */
function admin_toolbar_tools_entity_insert(EntityInterface $entity) {
  // Skip rebuild during config sync because rebuild should
  // always be a post-sync step.
  if (!\Drupal::isConfigSyncing()) {
    $entities = \Drupal::service('admin_toolbar_tools.helper')->getRebuildEntityTypes();
    if (in_array($entity->getEntityTypeId(), $entities)) {
      \Drupal::service('plugin.manager.menu.link')->rebuild();
    }
  }
}

/**
 * Implements hook_entity_update().
 */
function admin_toolbar_tools_entity_update(EntityInterface $entity) {
  // Skip rebuild during config sync because rebuild should
  // always be a post-sync step.
  if (!\Drupal::isConfigSyncing()) {
    $entities = \Drupal::service('admin_toolbar_tools.helper')->getRebuildEntityTypes();
    if (in_array($entity->getEntityTypeId(), $entities)) {
      \Drupal::service('plugin.manager.menu.link')->rebuild();
    }
  }
}

/**
 * Implements hook_entity_delete().
 */
function admin_toolbar_tools_entity_delete(EntityInterface $entity) {
  // Skip rebuild during config sync because rebuild should
  // always be a post-sync step.
  if (!\Drupal::isConfigSyncing()) {
    $entities = \Drupal::service('admin_toolbar_tools.helper')->getRebuildEntityTypes();
    if (in_array($entity->getEntityTypeId(), $entities)) {
      \Drupal::service('plugin.manager.menu.link')->rebuild();
    }
  }
}
