<?php

/**
 * @file
 * Provides basic Blazy integration for lazy loading and multi-serving images.
 */

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Component\Serialization\Json;
use Drupal\Component\Utility\NestedArray;
use Drupal\blazy\Blazy;

/**
 * Implements hook_theme().
 */
function blazy_theme() {
  return ['blazy' => ['render element' => 'element']];
}

/**
 * Prepares variables for blazy.html.twig templates.
 */
function template_preprocess_blazy(&$variables) {
  Blazy::buildAttributes($variables);
}

/**
 * Overrides variables for responsive-image.html.twig templates.
 */
function blazy_preprocess_responsive_image(&$variables) {
  $config = Blazy::getConfig();

  // Do not proceed if disabled globally, or not a Blazy formatter.
  if (!$config['responsive_image'] || !isset($variables['attributes']['data-srcset'])) {
    return;
  }

  // We are here either using Blazy, or core Responsive image formatters.
  Blazy::preprocessResponsiveImage($variables);
}

/**
 * Implements hook_preprocess_field().
 */
function blazy_preprocess_field(array &$variables) {
  $element = $variables['element'];

  // Only proceed if an image field and using Blazy formatter.
  if (!isset($element['#blazy'])) {
    return;
  }

  // Defines [data-blazy] attribute as required by the Blazy loader.
  $settings = $element['#blazy'];
  $variables['attributes']['class'][] = 'blazy';
  $variables['attributes']['data-blazy'] = empty($settings['blazy_data']) ? '' : Json::encode($settings['blazy_data']);
  if (!empty($settings['media_switch'])) {
    $switch = str_replace('_', '-', $settings['media_switch']);
    $variables['attributes']['data-' . $switch . '-gallery'] = TRUE;
  }
}

/**
 * Implements hook_views_pre_render().
 */
function blazy_views_pre_render($view) {
  if (!isset($view)) {
    return;
  }
  \Drupal\blazy\BlazyViews::viewsPreRender($view);
}

/**
 * Implements hook_field_formatter_info_alter().
 */
function blazy_field_formatter_info_alter(array &$info) {
  // Supports optional Media Entity via VEM/VEF if available.
  $common = [
    'description' => t('Displays lazyloaded images, or iframes, for VEF/ ME.'),
    'quickedit'   => ['editor' => 'disabled'],
    'provider'    => 'blazy',
  ];

  if (\Drupal::moduleHandler()->moduleExists('video_embed_media')) {
    $info['blazy_file'] = $common + [
      'id'          => 'blazy_file',
      'label'       => t('Blazy Image with Media'),
      'class'       => 'Drupal\blazy\Plugin\Field\FieldFormatter\BlazyFileFormatter',
      'field_types' => ['entity_reference', 'image'],
    ];

    $info['blazy_video'] = $common + [
      'id'          => 'blazy_video',
      'label'       => t('Blazy Video'),
      'class'       => 'Drupal\blazy\Plugin\Field\FieldFormatter\BlazyVideoFormatter',
      'field_types' => ['video_embed_field'],
    ];
  }
}

/**
 * Implements hook_config_schema_info_alter().
 */
function blazy_config_schema_info_alter(array &$definitions) {
  Blazy::configSchemaInfoAlter($definitions, 'blazy_base');
}

/**
 * Implements hook_library_info_alter().
 */
function blazy_library_info_alter(&$libraries, $extension) {
  if ($extension === 'blazy' && function_exists('libraries_get_path')) {
    $libraries['blazy']['js'] = ['/' . libraries_get_path('blazy') . '/blazy.min.js' => ['weight' => -4]];
  }
}

/**
 * Implements hook_blazy_attach_alter().
 */
function blazy_blazy_attach_alter(array &$load, $attach = []) {
  if (!empty($attach['colorbox'])) {
    $dummy = [];
    \Drupal::service('colorbox.attachment')->attach($dummy);
    $load = isset($dummy['#attached']) ? NestedArray::mergeDeep($load, $dummy['#attached']) : $load;
    $load['library'][] = 'blazy/colorbox';
    unset($dummy);
  }
}

/**
 * Implements hook_blazy_lightboxes_alter().
 */
function blazy_blazy_lightboxes_alter(array &$lightboxes) {
  if (is_file(DRUPAL_ROOT . '/libraries/photobox/photobox/jquery.photobox.js')) {
    $lightboxes[] = 'photobox';
  }
}

/**
 * Implements hook_blazy_settings_alter().
 */
function blazy_blazy_settings_alter(array &$build, $items) {
  $settings = &$build['settings'];

  // Sniffs for Views to allow block__no_wrapper, views_no_wrapper, etc.
  if (function_exists('views_get_current_view') && $view = views_get_current_view()) {
    $settings['view_name'] = $view->storage->id();
    $settings['current_view_mode'] = $view->current_display;
  }
}

/**
 * Implements hook_help().
 */
function blazy_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.blazy':
      return check_markup(file_get_contents(dirname(__FILE__) . '/README.txt'));
  }
}
