<?php

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

use Drupal\Component\Utility\NestedArray;
use Drupal\blazy\Blazy;
use Drupal\blazy\BlazyDefault;
use Drupal\blazy\BlazyViews;

/**
 * Provides a convenient shortcut for procedural hooks.
 *
 * @return class
 *   The Blazy manager class instance.
 */
function blazy() {
  static $manager;

  if (!isset($manager)) {
    $manager = \Drupal::service('blazy.manager');
  }

  return $manager;
}

/**
 * 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) {
  if (isset($variables['attributes']['data-b-lazy'])) {
    Blazy::preprocessResponsiveImage($variables);
  }
}

/**
 * Implements hook_preprocess_field().
 */
function blazy_preprocess_field(array &$variables) {
  // Only proceed if an image field and using Blazy formatter.
  if (isset($variables['element']['#blazy'])) {
    Blazy::containerAttributes($variables['attributes'], $variables['element']['#blazy']);
  }
}

/**
 * Implements hook_views_pre_render().
 */
function blazy_views_pre_render($view) {
  if (isset($view)) {
    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 (blazy()->getModuleHandler()->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' && $path = blazy_libraries_get_path('blazy')) {
    $libraries['blazy']['js'] = ['/' . $path . '/blazy.min.js' => ['weight' => -4]];
  }
}

/**
 * Implements hook_blazy_attach_alter().
 */
function blazy_blazy_attach_alter(array &$load, $attach = []) {
  if (!empty($attach['colorbox'])) {
    // Uninstalling colorbox without updating fields might break, bail out.
    if (function_exists('colorbox_theme')) {
      $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_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;
  }
}

/**
 * Alters blazy settings here due to static FormatterBase::defaultSettings().
 */
function blazy_alterable_settings(array &$settings) {
  return BlazyDefault::getInstance()->alterableSettings($settings);
}

/**
 * Provides a wrapper to replace deprecated libraries_get_path() at ease.
 */
function blazy_libraries_get_path($name, $base_path = FALSE) {
  $function = 'libraries_get_path';
  return is_callable($function) ? $function($name, $base_path) : FALSE;
}

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