<?php

/**
 * @file
 * Install/update hook implementations.
 */

/**
 * Delete the 'delete_media' action we used to provide, if it exists.
 *
 * Use the core 'media_delete_action' instead.
 */
function islandora_update_8001(&$sandbox) {
  $action = \Drupal::service('entity_type.manager')->getStorage('action')->load('delete_media');
  if ($action) {
    $action->delete();
  }
}

/**
 * Replaces 'entity_bundle' conditions with 'islandora_entity_bundle'.
 *
 * This prevents plugin naming collisions between islandora and ctools.
 */
function islandora_update_8002(&$sandbox) {

  // Find contexts that have the old 'entity_bundle' condition.
  $results = \Drupal::entityQuery('context')->condition('conditions.entity_bundle.id', 'entity_bundle')->execute();

  if (empty($results)) {
    return;
  }

  // Set each context config to use 'islandora_entity_bundle' instead.
  foreach ($results as $result) {
    $config = \Drupal::configFactory()->getEditable("context.context.$result");
    $condition = $config->get('conditions.entity_bundle');
    $condition['id'] = 'islandora_entity_bundle';
    $config->set('conditions.islandora_entity_bundle', $condition);
    $config->clear('conditions.entity_bundle');
    $config->save();
  }

  // Force drupal to reload the config.
  \Drupal::service('plugin.manager.condition')->clearCachedDefinitions();
}

/**
 * Deletes the islandora_version_count table.
 *
 * We never implemented the functionality.
 */
function islandora_update_8003(&$sandbox) {
  \Drupal::service('database')
    ->schema()
    ->dropTable('islandora_version_count');
}

/**
 * Renames migration source keys -> ids.
 */
function islandora_update_8004() {
  $config_factory = \Drupal::configFactory();
  $config = $config_factory->getEditable('migrate_plus.migration.islandora__tags');
  if ($config) {
    if (!$config->get('source.ids')) {
      $config->set('source.ids', $config->get('source.keys'));
      $config->clear('source.keys');
      $config->save(TRUE);
    }
  }
}