<?php

/**
 * @file
 * Functions to support theming in the Stable theme.
 */

use Drupal\Component\Utility\Html;

/**
 * Implements hook_library_info_alter().
 */
function stable_library_info_alter(&$libraries, $extension) {
  // Add removed css/filter.admin.css file back so that themes overriding
  // this file continue getting same behavior until Drupal 9.
  if ($extension === 'filter') {
    if (isset($libraries['drupal.filter.admin'])) {
      $libraries['drupal.filter.admin']['css']['theme']['css/filter.admin.css'] = [];
    }
    if (isset($libraries['drupal.filter'])) {
      $libraries['drupal.filter']['css']['theme']['css/filter.admin.css'] = [];
    }
  }
}

/**
 * Implements template_preprocess_links().
 */
function stable_preprocess_links(&$variables) {
  if (!empty($variables['links'])) {
    foreach ($variables['links'] as $key => $value) {
      if (!is_numeric($key)) {
        $class = Html::getClass($key);
        $variables['links'][$key]['attributes']->addClass($class);
      }
    }
  }
}

/**
 * Implements hook_element_info_alter().
 */
function stable_element_info_alter(array &$info) {
  if (array_key_exists('text_format', $info)) {
    $info['text_format']['#process'][] = 'stable_process_text_format';
  }
}

/**
 * #process callback, for adding classes to filter components.
 *
 * @param array $element
 *   Render array for the text_format element.
 *
 * @return array
 *   Text_format element with the filter classes added.
 */
function stable_process_text_format(array $element) {
  $element['format']['#attributes']['class'][] = 'filter-wrapper';
  $element['format']['guidelines']['#attributes']['class'][] = 'filter-guidelines';
  $element['format']['format']['#attributes']['class'][] = 'filter-list';
  $element['format']['help']['#attributes']['class'][] = 'filter-help';

  return $element;
}

/**
 * Implements hook_preprocess_image_widget().
 */
function stable_preprocess_image_widget(&$variables) {
  if (!empty($variables['element']['fids']['#value'])) {
    $file = reset($variables['element']['#files']);
    $variables['data']['file_' . $file->id()]['filename']['#suffix'] = ' <span class="file-size">(' . format_size($file->getSize()) . ')</span> ';
  }
}
