<?php

/**
 * @file
 * Contains dropzonejs.module.
 */

use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */
function dropzonejs_help($route_name, RouteMatchInterface $route_match) {
  $output = '';
  switch ($route_name) {
    // Main module help for the dropzonejs module.
    case 'help.page.dropzonejs':
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('DropzoneJS') . '</p>';
    default:
  }
  return $output;
}

/**
 * Implements hook_theme().
 */
function dropzonejs_theme() {
  return [
    'dropzonejs' => [
      'render element' => 'element',
    ],
  ];
}

/**
 * Prepares variables for dropzone form element.
 *
 * Default template: dropzonejs.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - element: A render element representing the file.
 */
function template_preprocess_dropzonejs(array &$variables) {
  $element = $variables['element'];

  $variables['attributes'] = [];
  if (isset($element['#id'])) {
    $variables['attributes']['id'] = $element['#id'];
  }
  if (!empty($element['#attributes']['class'])) {
    $variables['attributes']['class'] = (array) $element['#attributes']['class'];
  }

  $variables['dropzone_description'] = $element['#dropzone_description'];
  $variables['or_text'] = t('or');
  $variables['select_files_button_text'] = t('Select files');
  $variables['uploaded_files'] = $element['uploaded_files'];
}

/**
 * Implements hook_library_info_build().
 */
function dropzonejs_library_info_build() {
  $libraries = [];

  if (\Drupal::moduleHandler()->moduleExists('libraries')) {
    $exif_path = libraries_get_path('exif-js') . '/exif.js';
  }
  else {
    $exif_path = DRUPAL_ROOT . '/libraries/exif-js/exif.js';
  }

  if ($exif_found = file_exists($exif_path)) {
    $libraries['exif-js'] = [
      'title' => 'Exif',
      'website' => 'https://github.com/exif-js/exif-js',
      'version' => 'v2.3.0',
      'license' => [
        'name' => 'MIT',
        'url' => 'https://github.com/exif-js/exif-js/blob/master/LICENSE.md',
        'gpl-compatible' => TRUE,
      ],
      'js' => [
        '/libraries/exif-js/exif.js' => [],
      ],
    ];

  }

  return $libraries;
}

/**
 * Implements hook_library_info_alter().
 */
function dropzonejs_library_info_alter(&$libraries, $extension) {
  if ($extension == 'dropzonejs' && \Drupal::moduleHandler()->moduleExists('libraries')) {
    $libraries['dropzonejs']['js'] = ['/' . libraries_get_path('dropzone') . '/dist/min/dropzone.min.js' => []];
    $libraries['dropzonejs']['css']['component'] = ['/' . libraries_get_path('dropzone') . '/dist/min/dropzone.min.css' => []];

    if ($exif_path = libraries_get_path('exif-js')) {
      $libraries['exif-js']['js'] = ['/' . $exif_path . '/exif.js' => []];
    }
  }
}
