<?php

/**
 * @file
 * Contains template_suggestions_extra.module..
 */

use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */
function template_suggestions_extra_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the template_suggestions_extra module.
    case 'help.page.template_suggestions_extra':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('Add extra useful template suggestsions') . '</p>';
      return $output;

    default:
  }
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function template_suggestions_extra_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  // Add node type to page suggestions.
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    if (!is_object($node)) {
      $node = \Drupal::service('entity_type.manager')->getStorage('node')->load($node);
    }
  }

  if (isset($node) && is_object($node)) {
    $altered_suggestions = [];

    foreach ($suggestions as $suggestion) {
      $extra_suggeston = '';

      // Add node type after the wildcard.
      if ($suggestion === 'page__node__%') {
        $extra_suggeston = 'page__node__' . $node->getType();
      }

      $altered_suggestions[] = $suggestion;
      if ($extra_suggeston) {
        $altered_suggestions[] = $extra_suggeston;
      }
    }
    $suggestions = $altered_suggestions;
  }
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function template_suggestions_extra_theme_suggestions_comment_alter(array &$suggestions, array $variables) {
  $original = $variables['theme_hook_original'];
  $entity = $variables['elements']['#comment'];
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');

  $suggestions = [];
  $suggestions[] = $original;
  $suggestions[] = $original . '__' . $sanitized_view_mode;
  $suggestions[] = $original . '__' . $entity->bundle();
  $suggestions[] = $original . '__' . $entity->bundle() . '__' . $sanitized_view_mode;
  $suggestions[] = 'comment__' . $sanitized_view_mode;

  return $suggestions;
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function template_suggestions_extra_theme_suggestions_field_alter(array &$suggestions, array $variables) {
  $element = $variables['element'];
  $suggestions[] = 'field__' . $element['#entity_type'] . '__type__' . $element['#field_type'];

  return $suggestions;
}
