<?php

/**
 * @file
 * Deployment scripts for Disign.
 */

/**
 * Migrates the node_view_mode field to field_display_mode.
 */
function disign_deploy_001_migrate_image_slide_view_mode(array &$sandbox): string {
  /** @var \Drupal\update_script_helpers\UpdateScriptHelper $helper */
  $helper = Drupal::service('update_script_helpers.update_script_helper');
  return $helper->copyField(
    $sandbox,
    'image_slide',
    'node_view_mode',
    'field_display_mode'
  );
}

/**
 * Set default value of new color_mode field.
 */
function disign_deploy_002_color_mode(array &$sandbox): string {
  /** @var \Drupal\update_script_helpers\UpdateScriptHelper $helper */
  $helper = Drupal::service('update_script_helpers.update_script_helper');
  $bundles = [
    'gallery_slide',
    'image_slide',
    'info_slide',
    'teaser_slide',
    'title_screen_slide',
    'video_slide',
  ];
  return $helper->setDefaultValue($sandbox, $bundles, 'field_color_mode');
}

/**
 * Set default value for new intial field in slidesets.
 */
function disign_deploy_003_slideset_initial(array &$sandbox): string {
  /** @var \Drupal\update_script_helpers\UpdateScriptHelper $helper */
  $helper = Drupal::service('update_script_helpers.update_script_helper');
  $entities = $helper->getEntities($sandbox, 'slide_set');
  $source_field = 'title';
  $dest_field = 'field_plaintext';
  foreach ($entities as $entity) {
    $sandbox['progress']++;
    $sandbox['current_pk'] = $entity->id();
    if (!$entity->hasField($source_field) || !$entity->hasField($dest_field)) {
      continue;
    }
    if (!$entity->get($dest_field)->isEmpty()) {
      continue;
    }
    $initial = strtoupper(substr($entity->get($source_field)->getString(), 0, 1));
    $entity->set($dest_field, $initial);
    $entity->save();
    $sandbox['updated']++;
  }

  return $helper->finishRun($sandbox);
}

/**
 * Set the default value of the new object_fit field in teaser slides.
 */
function disign_deploy_004_object_fit_teaser(array &$sandbox): string {
  /** @var \Drupal\update_script_helpers\UpdateScriptHelper $helper */
  $helper = Drupal::service('update_script_helpers.update_script_helper');
  return $helper->setDefaultValue($sandbox, 'teaser_slide', 'field_object_fit');
}

/**
 * Copy the value of the old display_mode field to the new object_fit field.
 */
function disign_deploy_005_object_fit_image(array &$sandbox): string {
  /** @var \Drupal\update_script_helpers\UpdateScriptHelper $helper */
  $helper = Drupal::service('update_script_helpers.update_script_helper');
  return $helper->copyField($sandbox, 'image_slide', 'field_display_mode', 'field_object_fit');
}
