<?php

/**
 * @file
 * Theme and preprocess functions for media.
 */

use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;

/**
 * Implements hook_preprocess_media().
 *
 * Attach libraries based on classes attached to the view mode.
 */
function sector_theme_preprocess_media(&$variables) {
  $media = $variables['elements']['#media'];

  switch ($media->bundle()) {
    case 'image':

      if ($media->hasField('field_brightness') && !$media->get('field_brightness')->isEmpty()) {
        $brightness = $media->get('field_brightness')->getValue();
      }

      if (isset($brightness[0])) {
        $variables['attributes']['class'][] = $brightness[0]['value'];
      }

      $fid = $media->field_media_image->target_id;

      $file = File::load($fid);

      $image_style = ImageStyle::load('preload');

      if ($image_style) {
        // Generate the styled image URL.
        $styled_image_url = $image_style->buildUrl($file->getFileUri());
        $variables['attributes']['style'] = '--placeholder: url('.$styled_image_url.')';

        $meta_tag = array(
          '#tag' => 'link',
          '#attributes' => array(
            'rel' => 'preload',
            'as' => 'image',
            'href' => $styled_image_url,
            'fetchpriority' => 'high',
          ),
        );

        $variables['#attached']['html_head'][] = array($meta_tag, 'preload_placeholder');
      }
      break;
  }
}
