<?php

/**
 * Gallery preprocess.
 *
 * @param $entity
 * @param $field_name
 * @param $vars
 */
function toc_emr_gallery_preprocess($entity, $field_name, &$vars) {
  $media_ids = _tm_misc_get_field_content($entity, $field_name, 'string', [], -1);
  $images = [];
  foreach (explode(', ', $media_ids) as $media_id) {
    $storage = \Drupal::service('entity_type.manager')->getStorage('media');
    $media = $storage->load($media_id);
    $caption = _tm_misc_get_field_content($media, 'name');
    $thumb = _tm_misc_get_styled_images_from_media($media_id, 'square_thumbnail', 'field_media_image', 'media', 'url_alt');
    $main = _tm_misc_get_styled_images_from_media($media_id, 'gallery', 'field_media_image', 'media', 'url_alt');
    if (!empty($thumb['url']) && !empty($main['url'])) {
      $images[] = [
        'caption' => $caption,
        'thumb' => $thumb['url'],
        'main' => $main['url'],
      ];
    }
  }
  $vars['images'] = $images;
  $vars['gid'] = _tm_misc_get_unique_field_id($entity, 'gallery');
}

/**
 * Preprocess for field gallery images, from ECK Gallery.
 */
function toc_emr_preprocess_field__gallery__field_gallery_image(&$vars) {
  $element = $vars['element'];
  $entity = $element['#object'];
  toc_emr_gallery_preprocess($entity, 'field_gallery_image', $vars);
}

/**
 * Preprocess for field images, from Commercial filming nodes.
 */
function toc_emr_preprocess_field__node__field_images(&$vars) {
  $element = $vars['element'];
  $entity = $element['#object'];
  toc_emr_gallery_preprocess($entity, 'field_images', $vars);
}