<?php

/**
 * @file
 * Install, update and uninstall functions for the dropzonejs module.
 */

/**
 * Implements hook_requirements().
 */
function dropzonejs_requirements($phase) {

  $requirements = [];

  // @todo Remove this conditional structure in favor of using the libraries
  // directory file finder service when Drupal 8.9 is the minimum supported
  // version of core.
  if (\Drupal::hasService('library.libraries_directory_file_finder')) {
    /** @var \Drupal\Core\Asset\LibrariesDirectoryFileFinder $library_file_finder */
    $library_file_finder = \Drupal::service('library.libraries_directory_file_finder');
    $library_found = (bool) $library_file_finder->find('dropzone/dist/min/dropzone.min.js');
  }
  else {
    $path = DRUPAL_ROOT . '/libraries/dropzone/dist/min/dropzone.min.js';
    if (\Drupal::moduleHandler()->moduleExists('libraries')) {
      $path = libraries_get_path('dropzone') . '/dist/min/dropzone.min.js';
    }

    // Is the library found in the root libraries path.
    $library_found = file_exists($path);

    // If library is not found, then look in the current profile libraries path.
    if (!$library_found) {
      $profile_path = drupal_get_path('profile', \Drupal::installProfile());
      $profile_path .= '/libraries/dropzone/dist/min/dropzone.min.js';
      // Is the library found in the current profile libraries path.
      $library_found = file_exists($profile_path);
    }
  }

  if (!$library_found) {
    $requirements['dropzonejs_library'] = [
      'title' => t('Dropzone library missing'),
      'description' => t('Dropzonejs requires the dropzone.min.js library.
        Download it (https://github.com/enyo/dropzone) and place it in the
        libraries folder (/libraries)'),
      'severity' => REQUIREMENT_ERROR,
    ];
  }

  return $requirements;
}

/**
 * The upload handler should use stream wrappers.
 */
function dropzonejs_update_8001() {
  $config_factory = \Drupal::configFactory();
  $config = $config_factory->getEditable('dropzonejs.settings');
  $config->clear('tmp_dir');
  $config->set('tmp_upload_scheme', 'temporary');
  $config->save(TRUE);
}

/**
 * Set default value for transliterate file name.
 */
function dropzonejs_update_8002() {
  $config_factory = \Drupal::configFactory();
  $config = $config_factory->getEditable('dropzonejs.settings');
  $config->clear('filename_transliteration');
  $config->set('filename_transliteration', TRUE);
  $config->save(TRUE);
}

/**
 * Set default value for upload timeout.
 */
function dropzonejs_update_8003() {
  $config_factory = \Drupal::configFactory();
  $config = $config_factory->getEditable('dropzonejs.settings');
  $config->clear('upload_timeout_ms');
  $config->set('upload_timeout_ms', 0);
  $config->save(TRUE);
}
