<?php

/**
 * @file
 * Install, update and uninstall functions for the profilename install profile.
 */

use Drupal\Core\Config\FileStorage;
use Drupal\Core\Extension\MissingDependencyException;
use Drupal\d_p\ParagraphSettingTypesInterface;
use Drupal\d_p\Plugin\Field\FieldType\ConfigurationStorage;
use Drupal\field\Entity\FieldConfig;
use Drupal\user\Entity\Role;
use Drupal\we_megamenu\WeMegaMenuBuilder;

/**
 * Implements hook_install().
 *
 * Perform actions to set up the site for this profile.
 *
 * @see system_install()
 */
function droopler_install() {
  // First, do everything in standard profile.
  include_once DRUPAL_ROOT . '/core/profiles/standard/standard.install';
  standard_install();

  \Drupal::configFactory()
    ->getEditable('node.settings')
    ->set('use_admin_theme', TRUE)
    ->save();

  \Drupal::configFactory()
    ->getEditable('system.site')
    ->set('default_langcode', 'en')
    ->set('page.front', '/node/1')
    ->save();

  /** @var \Drupal\Core\Extension\ModuleInstaller $module_installer */
  $module_installer = \Drupal::service('module_installer');

  /** @var \Drupal\Core\Extension\ModuleHandler $module_handler */
  $module_handler = \Drupal::service('module_handler');

  // Install init content. It will add an install task to be performed later.
  $module_installer->install(['d_content_init']);

  // Try to install custom init that alters the original one.
  if ($module_handler->moduleExists('d_custom_init')) {
    $module_installer->install(['d_custom_init']);
  }
  else {
    \Drupal::logger('droopler_install')
      ->notice('Custom content init not detected.');
  }

  // Remove footer menu to avoid fatal error while trying to edit it
  // because of missing route.
  \Drupal::configFactory()->getEditable('system.menu.footer')->delete();

  // Set droopler_theme as default.
  \Drupal::configFactory()
    ->getEditable('system.theme')
    ->set('default', 'droopler_theme')
    ->set('admin', 'claro')
    ->save();
}

/**
 * Implements hook_install_tasks().
 */
function droopler_install_tasks() {
  $tasks = [
    'droopler_additional_components_form' => [
      'display_name' => t('Enable additional components'),
      'type' => 'form',
      'function' => 'Drupal\droopler\Installer\Form\AdditionalComponentsForm',
    ],
    'droopler_additional_components_install' => [
      'display_name' => t('Install additional components'),
      'type' => 'batch',
    ],
    'droopler_enable_subtheme_batch' => [
      'display' => TRUE,
      'display_name' => t('Install and enable subtheme'),
      'type' => 'batch',
    ],
  ];
  return $tasks;
}

/**
 * Install additional components in a batch.
 *
 * @param array $install_state
 *   The install state.
 *
 * @return array
 *   Batch array.
 */
function droopler_additional_components_install(array &$install_state) {
  $modules = $install_state['droopler_additional_modules'];
  $init_content = $install_state['droopler_init_content'];

  $batch = $operations = [];
  if ($modules) {
    foreach ($modules as $module) {
      $operations[] = [
        'droopler_install_module',
        [$module],
      ];
    }
  }

  if ($init_content) {
    $init_content_batch = droopler_enable_init_content_batch();
    foreach ($init_content_batch['operations'] as $operation) {
      $operations[] = $operation;
    }
  }

  if (!empty($operations)) {
    $batch = [
      'operations' => $operations,
      'title' => t('Installing selected components'),
      'error_message' => t('Installation error.'),
    ];
  }

  return $batch;
}

/**
 * Allow to install a single module using module_installer service.
 *
 * @param string $module
 *   Module machine name.
 * @param array $context
 *   Batch context.
 */
function droopler_install_module(string $module, array &$context) {
  \Drupal::service('module_installer')->install([$module], TRUE);
  $context['message'] = t('Installed %module module.', ['%module' => $module]);
}

/**
 * Import a config file.
 *
 * @param string $module
 *   Module name.
 * @param string $name
 *   Config file name without .yml extension.
 *
 * @todo To be moved to a new manager class.
 */
function _droopler_import_config($module, $name) {
  $config_path = \Drupal::service('extension.path.resolver')->getPath('module', $module) . '/config/install';
  $source = new FileStorage($config_path);
  $config_storage = \Drupal::service('config.storage');
  $config_storage->write($name, $source->read($name));
}

/**
 * Install d_product.
 *
 * @param int $step
 *   Current installation step.
 * @param array $context
 *   Batch context.
 */
function droopler_enable_product(int $step, array &$context) {
  switch ($step) {
    case 1:
      droopler_install_module('d_product', $context);
      break;

    case 2:
      \Drupal::service('config.installer')->installOptionalConfig();
      $context['message'] = t('Optional config installed');
      break;
  }
}

/**
 * Batch content init creating.
 *
 * @return array
 *   Batch defintion.
 */
function droopler_enable_init_content_batch() {
  $types = [
    'block',
    'media',
    'content',
    'block_second_run',
    'index_content',
  ];

  $operations = [];
  foreach ($types as $type) {
    $operations[] = ['d_content_init_create_all_batch', [$type]];
  }

  return [
    'operations' => $operations,
    'title' => t('Init content'),
  ];
}

/**
 * Batch enable of subtheme.
 *
 * @return array
 *   Batch defintion.
 */
function droopler_enable_subtheme_batch() {
  return [
    'operations' => [
      ['droopler_enable_subtheme', []],
      ['droopler_enable_subtheme_postprocess', []],
    ],
    'title' => t('Install and enable subtheme'),
  ];
}

/**
 * Enable subtheme.
 *
 * @param array $context
 *   Batch context.
 */
function droopler_enable_subtheme(array &$context) {
  try {
    \Drupal::service('theme_installer')->install(['droopler_subtheme']);
    \Drupal::configFactory()
      ->getEditable('system.theme')
      ->set('default', 'droopler_subtheme')
      ->set('admin', 'claro')
      ->save();
    $context['message'] = t('Installed %theme theme', ['%theme' => 'droopler_subtheme']);
  }
  catch (Exception $e) {
    \Drupal::logger('droopler_install')->notice('No subtheme detected.');
    $context['message'] = t('%theme theme not detected, skipping theme installation.', ['%theme' => 'droopler_subtheme']);
  }
}

/**
 * Additional operations after subtheme installation.
 *
 * All those operations have to be executed after installation of the subtheme.
 * We can think about to place them in the droopler_subtheme.install file when
 * this functionality will be implemented.
 *
 * @param array $context
 *   Batch context.
 *
 * @see: https://www.drupal.org/project/drupal/issues/2652542
 * @see: https://www.drupal.org/node/2937955
 */
function droopler_enable_subtheme_postprocess(array &$context) {
  if (!\Drupal::service('theme_handler')->themeExists('droopler_subtheme')) {
    $context['message'] = t('Theme %theme not installed, skipping postinstall operations', ['%theme' => 'droopler_subtheme']);
  }
  else {

    // Set logo same as on base theme if custom path has been defined there.
    $base_settings = Drupal::configFactory()
      ->getEditable('droopler_theme.settings');
    if (!$base_settings->get('logo.use_default')
      && $logo_path = $base_settings->get('logo.path')) {
      $current_settings = Drupal::configFactory()
        ->getEditable('droopler_subtheme.settings');
      $current_settings->set('logo.use_default', FALSE);
      $current_settings->set('logo.path', $logo_path);
      $current_settings->save();
    }

    // Copy configuration of the WeMegaMenu from base to subtheme.
    if ($base_menu = WeMegaMenuBuilder::loadConfig('main', 'droopler_theme')) {
      WeMegaMenuBuilder::saveConfig('main', 'droopler_subtheme', json_encode($base_menu));
      \Drupal::cache('render')->invalidateAll();
    }

    $context['message'] = t('Theme %theme configured.', ['%theme' => 'droopler_subtheme']);
  }
}

/**
 * Performs config update of specified modules.
 *
 * Configs should be placed in respective module directories e.g
 * "module/config/update/moduleName.updateNumber.yml".
 *
 * @param array $modules
 *   Array of module names to update.
 * @param string|int $update_number
 *   Number of the update corresponding to the droopler update number.
 *
 * @return bool
 *   Status of the modules configuration update.
 */
function update_modules_configuration(array $modules, $update_number) {
  $status = [];
  $updater = \Drupal::service('d_update');
  $module_handler = \Drupal::service('module_handler');
  foreach ($modules as $module) {
    if ($module_handler->moduleExists($module)) {
      $update = $updater->updateConfigurations("module/{$module}", "{$module}.{$update_number}");
      if (!$update) {
        \Drupal::logger($module)->error('The configuration update for the module failed');
        $status[] = $update;
      }
    }
  }
  return !in_array(FALSE, $status);
}

/**
 * Returns array of names of all existing entities bundles.
 *
 * @return array
 *   Array with all entities bundles.
 */
function get_all_entity_bundles() {
  $entityBundles = \Drupal::service('entity_type.manager')
    ->getAllBundleInfo();
  $bundles = [];
  foreach ($entityBundles as $entityBundle) {
    foreach ($entityBundle as $bundle => $information) {
      $bundles[] = $bundle;
    }
  }

  return $bundles;
}

/**
 * Returns a list of modules to install, based on the list of required modules.
 *
 * @param array $modules
 *   Array of required modules.
 *
 * @return array
 *   Array of modules that actually need installing.
 */
function calculate_modules_for_install(array $modules) {
  $module_handler = \Drupal::service('module_handler');
  $modulesToInstall = [];
  foreach ($modules as $module) {
    if (!$module_handler->moduleExists($module)) {
      $modulesToInstall[] = $module;
    }
  }

  return $modulesToInstall;
}

/**
 * Droopler 1.3 Updates.
 */
function droopler_update_8101() {
  $module_installer = \Drupal::service('module_installer');

  // Install modules.
  $modules = [
    'd_p_counters',
    'd_p_gallery',
    'd_p_side_embed',
    'd_p_side_tiles',
    'd_p_tiles',
    'colorbox',
    'd_p_help',
  ];
  $module_installer->install($modules, TRUE);

  // Install config.
  _droopler_import_config('d_content', 'field.field.node.content_page.field_page_section');
}

/**
 * Droopler 1.4 Updates.
 */
function droopler_update_8102() {
  $values = [];

  /** @var Drupal\Core\Extension\ModuleInstallerInterface $module_installer */
  $module_installer = \Drupal::service('module_installer');

  // Install checklistapi and d_update modules.
  try {
    $modules = [
      'checklistapi',
      'd_update',
    ];
    $result = $module_installer->install($modules, TRUE);
    $values['droopler__droopler_update_8102_0'] = $result;
    $values['droopler__droopler_update_8102_1'] = $result;
  }
  catch (MissingDependencyException $e) {
    $values['droopler__droopler_update_8102_0'] = FALSE;
    $values['droopler__droopler_update_8102_1'] = FALSE;
  }

  /** @var Drupal\d_update\Updater $updater */
  $updater = \Drupal::service('d_update');

  // Install editor role.
  $configs = [
    'd_content' => [
      'user.role.d_editor' => '',
    ],
  ];
  $values['droopler__droopler_update_8102_2'] = $updater->importConfigs($configs);

  // Update blog post config.
  $configs = [
    'd_blog' => [
      'core.entity_view_display.node.blog_post.thumbnail' => '',
      'core.entity_view_mode.node.thumbnail' => '',
    ],
  ];
  $values['droopler__droopler_update_8102_3'] = $updater->importConfigs($configs);

  // Update fields config.
  $configs = [
    'd_p_carousel' => [
      'field.field.paragraph.d_p_carousel.field_d_icon' => '',
      'field.field.paragraph.d_p_carousel_item.field_d_image' => '',
    ],
    'd_blog' => [
      'field.field.node.blog_post.field_blog_main_image' => '',
      'field.field.paragraph.d_p_blog_image.field_d_image' => '',
    ],
    'd_p_banner' => [
      'field.field.paragraph.d_p_banner.field_d_icon' => '',
      'field.field.paragraph.d_p_banner.field_d_image_background' => '',
    ],
    'd_p_counters' => [
      'field.field.paragraph.d_p_group_of_counters.field_d_icon' => '',
      'field.field.paragraph.d_p_group_of_counters.field_d_image_background' => '',
    ],
    'd_p_form' => [
      'field.field.paragraph.d_p_form.field_d_icon' => '',
      'field.field.paragraph.d_p_form.field_d_image_background' => '',
    ],
    'd_p_gallery' => [
      'field.field.paragraph.d_p_gallery.field_d_icon' => '',
      'field.field.paragraph.d_p_gallery.field_d_image' => '',
    ],
    'd_p_side_embed' => [
      'field.field.paragraph.d_p_side_embed.field_d_icon' => '',
    ],
    'd_p_side_image' => [
      'field.field.paragraph.d_p_side_image.field_d_icon' => '',
      'field.field.paragraph.d_p_side_image.field_d_image_background' => '',
    ],
    'd_p_side_tiles' => [
      'field.field.paragraph.d_p_side_tiles.field_d_icon' => '',
      'field.field.paragraph.d_p_side_tiles.field_d_image' => '',
    ],
    'd_p_subscribe_file' => [
      'field.field.paragraph.d_p_subscribe_file.field_d_icon' => '',
      'field.field.paragraph.d_p_subscribe_file.field_d_image_background' => '',
    ],
    'd_p_text_blocks' => [
      'field.field.paragraph.d_p_group_of_text_blocks.field_d_icon' => '',
      'field.field.paragraph.d_p_single_text_block.field_d_icon' => '',
    ],
    'd_p_text_paged' => [
      'field.field.paragraph.d_p_text_paged.field_d_icon' => '',
    ],
    'd_p_text_with_bckg' => [
      'field.field.paragraph.d_p_text_with_bckg.field_d_icon' => '',
      'field.field.paragraph.d_p_text_with_bckg.field_d_image_background' => '',
    ],
    'd_p_tiles' => [
      'field.field.paragraph.d_p_tiles.field_d_icon' => '',
      'field.field.paragraph.d_p_tiles.field_d_image' => '',
    ],
  ];
  $values['droopler__droopler_update_8102_4'] = $updater->importConfigs($configs);

  // Install geysir and d_geysir modules.
  try {
    $modules = [
      'geysir',
      'd_geysir',
    ];
    $result = $module_installer->install($modules, TRUE);
    $values['droopler__droopler_update_8102_5'] = $result;
    $values['droopler__droopler_update_8102_6'] = $result;
  }
  catch (MissingDependencyException $e) {
    $values['droopler__droopler_update_8102_5'] = FALSE;
    $values['droopler__droopler_update_8102_6'] = FALSE;
  }

  // Update blog post metatags.
  $configs = [
    'd_blog' => [
      'metatag.metatag_defaults.node__blog_post' => '',
    ],
  ];
  $values['droopler__droopler_update_8102_7'] = $updater->importConfigs($configs);

  $progress = [
    'v1.3' => [],
    'v1.4' => $values,
  ];

  // Mark 1.3 update as successfull.
  for ($i = 0; $i <= 7; $i++) {
    $progress['v1.3']['droopler__droopler_update_8101_' . $i] = TRUE;
  }
  $updater->checklist()->saveProgress($progress);
}

/**
 * Droopler 2.0 Updates.
 */
function droopler_update_8103() {
  /** @var Drupal\Core\Extension\ModuleInstallerInterface $module_installer */
  $module_installer = \Drupal::service('module_installer');

  /** @var Drupal\d_update\Updater $updater */
  $updater = \Drupal::service('d_update');

  // Remove footer menu menu to avoid fatal error while trying to edit it
  // because of missing route.
  \Drupal::configFactory()->getEditable('system.menu.footer')->delete();

  // Migrate old saved checklist configs to new state storage.
  $updater->checklist()->migrateConfigProgressToStateProgress();

  // Install contrib modules.
  try {
    $modules = [
      'entity_reference_display',
      'we_megamenu',
    ];
    $result = $module_installer->install($modules, TRUE);
    $values['droopler__droopler_update_8103_0'] = $result;
  }
  catch (MissingDependencyException $e) {
    $values['droopler__droopler_update_8103_0'] = FALSE;
  }
  // Import new configs for d_p.
  $updater->importConfigs([
    'd_p' => [
      'field.storage.paragraph.field_d_background_color' => '',
      'field.storage.paragraph.field_d_node_reference' => '',
      'field.storage.paragraph.field_d_settings' => '',
    ],
  ]);
  // Check if any 1.4 custom modules are not installed and install them.
  try {
    $modules = calculate_modules_for_install([
      'd_content',
      'd_geysir',
      'd_lang_dropdown',
      'd_p',
      'd_p_banner',
      'd_p_carousel',
      'd_p_counters',
      'd_p_form',
      'd_p_gallery',
      'd_p_help',
      'd_p_side_embed',
      'd_p_side_image',
      'd_p_side_tiles',
      'd_p_subscribe_file',
      'd_p_text_blocks',
      'd_p_text_paged',
      'd_p_text_with_bckg',
      'd_p_tiles',
      'd_update',
    ]);
    $values['droopler__droopler_update_8103_1'] = $module_installer->install($modules, TRUE);
  }
  catch (MissingDependencyException $e) {
    $values['droopler__droopler_update_8103_1'] = FALSE;
  }

  // Activate new 2.0 modules.
  try {
    $modules = [
      'd_p_node',
      'd_p_side_by_side',
      'd_search',
      'd_social_media',
      'd_p_reference_content',
    ];
    $result = $module_installer->install($modules, TRUE);
    $values['droopler__droopler_update_8103_2'] = $result;
  }
  catch (MissingDependencyException $e) {
    $values['droopler__droopler_update_8103_2'] = FALSE;
  }

  // Add new fields to paragraphs.
  $configs = [
    'd_p_banner' => [
      'field.field.paragraph.d_p_banner.field_d_settings' => '',
    ],
    'd_p_carousel' => [
      'field.field.paragraph.d_p_carousel.field_d_settings' => '',
      'field.field.paragraph.d_p_carousel_item.field_d_settings' => '',
    ],
    'd_p_counters' => [
      'field.field.paragraph.d_p_group_of_counters.field_d_settings' => '',
      'field.field.paragraph.d_p_single_counter.field_d_settings' => '',
    ],
    'd_p_gallery' => [
      'field.field.paragraph.d_p_gallery.field_d_settings' => '',
    ],
    'd_p_form' => [
      'field.storage.paragraph.field_d_layout_modifier' => '',
      'field.field.paragraph.d_p_form.field_d_layout_modifier' => '',
      'field.field.paragraph.d_p_form.field_d_long_text' => '',
      'field.field.paragraph.d_p_form.field_d_settings' => '',
    ],
    'd_p_side_image' => [
      'field.field.paragraph.d_p_side_image.field_d_background_color' => '',
      'field.field.paragraph.d_p_side_image.field_d_settings' => '',
    ],
    'd_p_side_tiles' => [
      'field.field.paragraph.d_p_side_tiles.field_d_settings' => '',
    ],
    'd_p_subscribe_file' => [
      'field.field.paragraph.d_p_subscribe_file.field_d_settings' => '',
    ],
    'd_p_side_embed' => [
      'field.field.paragraph.d_p_side_embed.field_d_settings' => '',
    ],
    'd_p_text_blocks' => [
      'field.field.paragraph.d_p_group_of_text_blocks.field_d_long_text' => '',
      'field.field.paragraph.d_p_group_of_text_blocks.field_d_settings' => '',
      'field.field.paragraph.d_p_single_text_block.field_d_background_color' => '',
      'field.field.paragraph.d_p_single_text_block.field_d_settings' => '',
    ],
    'd_p_text_paged' => [
      'field.field.paragraph.d_p_text_paged.field_d_settings' => '',
    ],
    'd_p_text_with_bckg' => [
      'field.field.paragraph.d_p_text_with_bckg.field_d_settings' => '',
    ],
    'd_p_tiles' => [
      'field.field.paragraph.d_p_tiles.field_d_settings' => '',
    ],
  ];
  $values['droopler__droopler_update_8103_3'] = $updater->importConfigs($configs);

  // Update existing fields.
  $configs = [
    'd_content' => [
      'field.field.node.content_page.field_page_section' => '43d9f25fcb0715eea8a9465388491269',
    ],
    'd_p_banner' => [
      'field.field.paragraph.d_p_banner.field_d_cta_link' => '63fe174a22c312e28faf3bc9fa41ce44',
    ],
    'd_p_side_image' => [
      'field.storage.paragraph.field_d_p_si_image_side' => '5d36513453cc08e7d015d68929ecddfc',
      'field.field.paragraph.d_p_side_image.field_d_cta_link' => 'ce47d9abef098da38cc53064c01d06d6',
    ],
    'd_p_side_embed' => [
      'field.field.paragraph.d_p_side_embed.field_d_cta_link' => '336654b916fc757f3af30239dc2d4976',
    ],
    'd_p_side_tiles' => [
      'field.field.paragraph.d_p_side_tiles.field_d_cta_link' => 'ac8fc9a194d17951a86e0a68371c12bb',
    ],
    'd_p_text_blocks' => [
      'field.field.paragraph.d_p_group_of_text_blocks.field_d_p_tb_block_reference' => '97dd017b20ad8add96ea20e13bbdea39',
      'field.field.paragraph.d_p_group_of_text_blocks.field_d_cta_link' => '12e9dbc1863b7bddb7cb6632b1a6d361',
    ],
    'd_p_text_paged' => [
      'field.field.paragraph.d_p_text_paged.field_d_cta_link' => 'ffda0c55cb64b91f1109971f67185970',
    ],
    'd_p_text_with_bckg' => [
      'field.field.paragraph.d_p_text_with_bckg.field_d_cta_link' => '27dca2ddd6b10a8cff0ec8c787c3dd9f',
    ],
  ];
  $values['droopler__droopler_update_8103_4'] = $updater->importConfigs($configs);

  // Update misc config.
  $configs = [
    'profile/droopler' => [
      'core.entity_form_display.contact_message.feedback.default' => '',
      // @todo These configs cause problems in logs, they must be double tested.
      // 'simple_sitemap.settings' => '38979e56edc0ee9369928a174dbc5578',
      // 'user.role.anonymous' => '4ea4b28e3275b7add9c389aec75a5216',
      // 'user.role.authenticated' => 'ca382ea635e3da6144322e05e5c3f4a8',
      'taxonomy.vocabulary.tags' => '43f9e4a277457349d58cedb7bbe1dc76',
    ],
    'd_content' => [
      'core.entity_view_display.node.content_page.d_small_box' => '',
      'simple_sitemap.bundle_settings.default.node.content_page' => '',
      'metatag.metatag_defaults.node__content_page' => 'e6d4f236df5d84f031d8edf6acfcd6da',
    ],
    'd_p_subscribe_file' => [
      'views.view.subscribe_file_paragraph' => '',
    ],
    // @todo We must check the behavior of the language switcher after update.
    // 'theme/droopler_theme' => [
    // 'block.block.languageswitcher' => 'b859a762deeb756585ae12b6dddcb25d',
    // ],
  ];
  $values['droopler__droopler_update_8103_5'] = $updater->importConfigs($configs);

  /** @var \Drupal\Core\Extension\ModuleHandler $module_handler */
  $module_handler = \Drupal::service('module_handler');
  if ($module_handler->moduleExists('d_blog')) {
    // Update d_blog config.
    $configs = [
      'd_blog' => [
        'metatag.metatag_defaults.node__blog_post' => '3e869dc915abd86f66f9b2d46d4fee2a',
        'core.entity_view_display.node.blog_post.d_small_box' => '',
        'core.entity_view_mode.node.teaser_small' => '',
        'core.entity_view_display.node.blog_post.teaser_small' => '',
        'pathauto.pattern.node_blog_pattern' => '',
        'responsive_image.styles.blog_images_style' => '5fffdeff846e07fe8c2e72f24ffab7f4',
        'core.entity_view_display.taxonomy_term.blog_posts_category.default' => 'acbf5d2748f47042c1171e66d48d1dc9',
        'taxonomy.vocabulary.blog_posts_category' => 'f2aa866752d8525f4dda0da49e99953b',
        'simple_sitemap.bundle_settings.default.node.blog_post' => '',
        'field.field.node.blog_post.field_blog_sections' => '1f6100447b6fff05e8b60f6f23cfaea5',
        'views.view.blog_listing' => 'e617972f67997f8d8f4c60eb29f49bd2',
      ],
    ];
    $values['droopler__droopler_update_8103_6'] = $updater->importConfigs($configs);
  }
  else {
    $values['droopler__droopler_update_8103_6'] = TRUE;
  }

  if ($module_handler->moduleExists('d_product')) {
    // Update d_product config.
    $configs = [
      'd_product' => [
        'field.field.node.d_product.field_page_section' => 'b691ac5762c4b87ed40f125f1772d7c1',
        'field.field.node.d_product.body' => '86148679c204177206e4aa1c7976a533',
        'views.view.product_images' => 'e72d8ee10d2d1192ce439c1fdd7287cf',
        'views.view.products_list' => '44b33ce68241349845d74959c90e5b72',
        'taxonomy.vocabulary.d_product_categories' => 'bb47ec12d4ea223256d81c442cde2783',
        'simple_sitemap.bundle_settings.node.d_product' => 'f8dcc16f0e902d016eb25ba28c27666c',
        'block.block.exposedformproducts_listproducts_list' => '64a616778f4788996d6f5ee44722a0ae',
        // @todo The updates below must be carefully tested, they can break existing sites (due to moved configs).
        'block.block.mobilefilterssubmit' => 'cf04a4ce3efb8e1db0594b00949644a2',
        'block.block.productcategoriestaxonomytermname' => '791b0420b472bb813403557acb2514c1',
        'block.block.resetfilters_2' => 'f45e47fc43e155355fbdffa3fd1c5173',
        'block.block.resetfilters' => '978cbc78d2875b9ec252b91b0347900d',
        'block.block.tagstaxonomytermname' => '419c970f6ffd428be18f995df7b6c097',
      ],
    ];
    $values['droopler__droopler_update_8103_7'] = $updater->importConfigs($configs);
  }
  else {
    $values['droopler__droopler_update_8103_7'] = TRUE;
  }

  if ($module_handler->moduleExists('we_megamenu')) {
    $configs = [
      'theme/droopler_theme' => [
        'block.block.mainnavigation' => 'override',
        'block.block.mainnavigation_2' => 'override',
      ],
    ];
    $values['droopler__droopler_update_8103_8'] = $updater->importConfigs($configs);

    if (\Drupal::service('theme_handler')
      ->getDefault() === 'droopler_subtheme') {
      $updater->instantiateBlocksForSubtheme('droopler_subtheme', $configs);
    }
  }

  $progress = [
    'v2.0' => $values,
  ];

  $updater->checklist()->saveProgress($progress);
}

/**
 * Droopler 2.0 Media migrate.
 */
function droopler_update_8104() {
  $entityBundles = get_all_entity_bundles();
  // Import all target Media Fields.
  /** @var Drupal\d_update\Updater $updater */
  $updater = \Drupal::service('d_update');

  $configs = [
    'd_content' => [
      'field.storage.node.field_teaser_media_image' => '',
      'field.field.node.content_page.field_teaser_media_image' => '',
    ],
    'd_p_banner' => [
      'field.field.paragraph.d_p_banner.field_d_media_background' => '',
      'field.field.paragraph.d_p_banner.field_d_media_icon' => '',
    ],
    'd_p_carousel' => [
      'field.field.paragraph.d_p_carousel.field_d_media_icon' => '',
      'field.field.paragraph.d_p_carousel_item.field_d_media_icon' => '',
    ],
    'd_p_counters' => [
      'field.field.paragraph.d_p_group_of_counters.field_d_media_background' => '',
      'field.field.paragraph.d_p_group_of_counters.field_d_media_icon' => '',
    ],
    'd_p_gallery' => [
      'field.field.paragraph.d_p_gallery.field_d_media_icon' => '',
      'field.field.paragraph.d_p_gallery.field_d_media_image' => '',
    ],
    'd_p_form' => [
      'field.field.paragraph.d_p_form.field_d_media_icon' => '',
      'field.field.paragraph.d_p_form.field_d_media_background' => '',
    ],
    'd_p_side_embed' => [
      'field.field.paragraph.d_p_side_embed.field_d_media_icon' => '',
    ],
    'd_p_side_image' => [
      'field.field.paragraph.d_p_side_image.field_d_media_icon' => '',
      'field.field.paragraph.d_p_side_image.field_d_media_background' => '',
    ],
    'd_p_side_tiles' => [
      'field.field.paragraph.d_p_side_tiles.field_d_media_icon' => '',
      'field.field.paragraph.d_p_side_tiles.field_d_media_image' => '',
    ],
    'd_p_subscribe_file' => [
      'field.field.paragraph.d_p_subscribe_file.field_d_media_icon' => '',
      'field.field.paragraph.d_p_subscribe_file.field_d_media_background' => '',
    ],
    'd_p_text_blocks' => [
      'field.field.paragraph.d_p_group_of_text_blocks.field_d_media_icon' => '',
      'field.field.paragraph.d_p_single_text_block.field_d_media_background' => '',
      'field.field.paragraph.d_p_single_text_block.field_d_media_icon' => '',
    ],
    'd_p_text_paged' => [
      'field.field.paragraph.d_p_text_paged.field_d_media_icon' => '',
    ],
    'd_p_text_with_bckg' => [
      'field.field.paragraph.d_p_text_with_bckg.field_d_media_icon' => '',
      'field.field.paragraph.d_p_text_with_bckg.field_d_media_background' => '',
    ],
    'd_p_tiles' => [
      'field.field.paragraph.d_p_tiles.field_d_media_icon' => '',
      'field.field.paragraph.d_p_tiles.field_d_media_image' => '',
    ],
  ];
  $values['droopler__droopler_update_8104_1'] = $updater->importConfigs($configs);

  $module_handler = \Drupal::service('module_handler');
  if ($module_handler->moduleExists('d_blog') && in_array('blog_post', $entityBundles)) {
    // Update d_blog config.
    $configs = [
      'd_blog' => [
        'core.entity_view_mode.media.d_blog_image' => '',
        'core.entity_view_display.media.d_image.d_blog_image' => '',
        'field.storage.node.field_blog_media_main_image' => '',
        'field.field.paragraph.d_p_blog_image.field_d_media_image' => '',
        'field.field.node.blog_post.field_blog_media_main_image' => '',
      ],
    ];
    $values['droopler__droopler_update_8104_2'] = $updater->importConfigs($configs);
  }
  else {
    $values['droopler__droopler_update_8104_2'] = TRUE;
  }
  if ($module_handler->moduleExists('d_product') && in_array('d_product', $entityBundles)) {
    // Update d_product config.
    $configs = [
      'd_product' => [
        'field.storage.node.field_d_product_media' => '',
        'field.field.node.d_product.field_d_product_media' => '',
      ],
    ];
    $values['droopler__droopler_update_8104_3'] = $updater->importConfigs($configs);
  }
  else {
    $values['droopler__droopler_update_8104_3'] = TRUE;
  }

  /**
   * Migrate images to media fields.
   *
   * @var \Drupal\d_content_init\ContentInitManagerMedia $media_manager
   */
  $media_manager = Drupal::service('d_content_init.manager_media');

  $fieldsToMigrate = [
    'field_d_icon' => 'field_d_media_icon',
    'field_d_image' => 'field_d_media_image',
    'field_d_image_background' => 'field_d_media_background',
    'field_blog_main_image' => 'field_blog_media_main_image',
    'field_teaser_image' => 'field_teaser_media_image',
    'field_product_image' => 'field_d_product_media',
  ];
  $fieldsMigrationSpecialCases = [
    'd_p_carousel_item' => [
      'field_d_image' => 'field_d_media_icon',
    ],
  ];

  /** @var \Drupal\Core\Entity\EntityStorageInterface $fieldStorage */
  $fieldStorage = \Drupal::entityTypeManager()
    ->getStorage('field_storage_config');

  $listOfMigratedFields = [];
  foreach ($fieldsToMigrate as $sourceFieldName => $targetFieldName) {
    $res = $fieldStorage->loadByProperties([
      'field_name' => $sourceFieldName,
    ]);

    /** @var \Drupal\field\Entity\FieldStorageConfig $storage */
    foreach ($res as $storage) {
      $bundles = $storage->getBundles();
      if (empty($bundles)) {
        \Drupal::logger('droopler_install')->notice("{$sourceFieldName} missing from active configuration. Skipping...");
        continue;
      }
      $entityType = $storage->getTargetEntityTypeId();

      $entities = \Drupal::entityTypeManager()
        ->getStorage($entityType)->loadByProperties([
          'type' => $bundles,
        ]);

      $errorsWhileMigrating = [];

      /** @var \Drupal\Core\Entity\ContentEntityBase $entity */
      foreach ($entities as $entity) {
        if (!$entity->hasField($sourceFieldName)) {
          continue;
        }

        /** @var \Drupal\file\Plugin\Field\FieldType\FileFieldItemList $sourceField */
        $sourceField = $entity->get($sourceFieldName);

        if ($sourceField->isEmpty()) {
          continue;
        }
        $entityTargetFieldName = $fieldsMigrationSpecialCases[$entity->bundle()][$sourceFieldName] ?? $targetFieldName;

        $sourceValues = $sourceField->getValue();

        try {
          foreach ($sourceValues as $sourceImage) {
            $media_entity = $media_manager->createMediaImageFromFid($sourceImage['target_id'], $sourceImage['alt']);
            $entity->get($entityTargetFieldName)->appendItem($media_entity);

          }
        }
        catch (InvalidArgumentException $e) {
          $errorsWhileMigrating[$entity->bundle()][$sourceField] = $sourceFieldName;

          \Drupal::logger('droopler_update')
            ->error('Exception while migrating media images for @sourceField to @targetField at @bundle @type.', [
              '@sourceField' => $sourceFieldName,
              '@targetField' => $entityTargetFieldName,
              '@bundle' => $entity->bundle(),
              '@type' => $entityType,
            ]);
        }

        $entity->save();
      }

      foreach ($bundles as $migratedBundle) {
        if (isset($errorsWhileMigrating[$migratedBundle][$sourceFieldName])) {
          continue;
        }
        $listOfMigratedFields[$entityType][$migratedBundle][$sourceFieldName] = $sourceFieldName;
      }
    }
  }

  $values['droopler__droopler_update_8104_4'] = TRUE;

  // Delete migrated fields.
  /** @var EntityFieldManager $entityFieldManager */
  $entityFieldManager = \Drupal::service('entity_field.manager');

  foreach ($listOfMigratedFields as $entityType => $migratedBundles) {
    foreach ($migratedBundles as $bundle => $migratedBundleFields) {
      $bundleAllFields = $entityFieldManager->getFieldDefinitions($entityType, $bundle);

      foreach ($migratedBundleFields as $fieldToDelete) {
        if (isset($bundleAllFields[$fieldToDelete])) {
          $bundleAllFields[$fieldToDelete]->delete();

          $newFieldName = $fieldsMigrationSpecialCases[$bundle][$fieldToDelete] ?? $fieldsToMigrate[$fieldToDelete];

          \Drupal::logger('droopler_update')
            ->info('Deleted @oldField field, it\'s values were migrated to @newField for all @bundle @type', [
              '@oldField' => $fieldToDelete,
              '@newField' => $newFieldName,
              '@bundle' => $bundle,
              '@type' => $entityType,
            ]);
        }
      }
    }
  }

  $values['droopler__droopler_update_8104_5'] = TRUE;

  $progress = [
    'v2.0' => $values,
  ];

  $updater->checklist()->saveProgress($progress);
}

/**
 * Droopler 2.0 Import all other modified configs after Media migrations.
 */
function droopler_update_8105() {
  /** @var Drupal\d_update\Updater $updater */
  $updater = \Drupal::service('d_update');

  $configs = [
    'd_content' => [
      'core.entity_form_display.node.content_page.default' => 'f865015c1a1baee972e8feb3d6c84d70',
      'core.entity_view_display.node.content_page.default' => '025e73620b1650aa03db407271cfe82d',
    ],
    'd_p_banner' => [
      'core.entity_form_display.paragraph.d_p_banner.default' => 'a4c8c186a27ad4ccbff3a7524ac5252d',
      'core.entity_view_display.paragraph.d_p_banner.default' => '7954851d78e5560369191f7bb0a217da',
      'paragraphs.paragraphs_type.d_p_banner' => '16d108c2d421a90beb935603c8c14a78',
    ],
    'd_p_carousel' => [
      'core.entity_form_display.paragraph.d_p_carousel.default' => 'ec0b8d9cbea4de5fed7ff999402468a5',
      'core.entity_form_display.paragraph.d_p_carousel_item.default' => '22fa1f375c118c22a0d61386f52eaeb4',
      'core.entity_view_display.paragraph.d_p_carousel.default' => '8cb8deae472852b756d97e56492996ee',
      'core.entity_view_display.paragraph.d_p_carousel_item.default' => '4841b060a4649cb5840a2fc7e05bdfd0',
      'field.field.paragraph.d_p_carousel.field_d_number' => '3459b028f5d3fea96796761757ad4cd0',
      'field.field.paragraph.d_p_carousel.field_d_p_cs_item_reference' => '37a919d8a4cd267ef42410e6024666ec',
      'field.field.paragraph.d_p_carousel_item.field_d_cta_link' => 'b73a7558b7145e365336a4050799064a',
      'field.field.paragraph.d_p_carousel_item.field_d_long_text' => 'e15fb286e519b0bac00257a2e90b6eba',
      'field.field.paragraph.d_p_carousel_item.field_d_main_title' => '07a25e47268ef25afbfb57181c15aa81',
      'paragraphs.paragraphs_type.d_p_carousel_item' => '5507c77f3f541f0a50d5803ed101abf3',
    ],
    'd_p_counters' => [
      'core.entity_form_display.paragraph.d_p_group_of_counters.default' => '5463576b8024a2794ad29a12a893e138',
      'core.entity_form_display.paragraph.d_p_single_counter.default' => 'e857d2f5142d2b0b29fc3c49f071eae6',
      'core.entity_view_display.paragraph.d_p_single_counter.default' => '5c2e672831135b05edfe811e5c6c85d5',
    ],
    'd_p_gallery' => [
      'core.entity_form_display.paragraph.d_p_gallery.default' => 'ef9210488f6c56af37b18aeb22914714',
      'core.entity_view_display.paragraph.d_p_gallery.default' => 'e072d082233ce6dbff8fd347c9382e70',
    ],
    'd_p_form' => [
      'core.entity_form_display.paragraph.d_p_form.default' => '19c0e40bdfb3f856e413f8c40655340b',
      'core.entity_view_display.paragraph.d_p_form.default' => 'b09d791838a2220defbcff2690b44f67',
      'field.field.paragraph.d_p_form.field_d_forms' => '5367bb67907496bca2fd3aa7b7821fd9',
      'paragraphs.paragraphs_type.d_p_form' => 'a1af3a95ce7dccf84daab9985f10cfa1',
    ],
    'd_p_side_embed' => [
      'core.entity_form_display.paragraph.d_p_side_embed.default' => '1ba5e544db6ef1b7725d78c1bb2b9362',
      'core.entity_view_display.paragraph.d_p_side_embed.default' => 'baa0d764c5f07d841efc22e0b53ff81b',
      'field.field.paragraph.d_p_side_embed.field_d_embed' => '10a700835004c1e0aa4dfbdad18aa427',
      'paragraphs.paragraphs_type.d_p_side_embed' => '75fa8419ebbd3470c10021c3c20d59a9',
    ],
    'd_p_side_image' => [
      'core.entity_form_display.paragraph.d_p_side_image.default' => '7f55328a7cfeda5bfad62785f231b959',
      'core.entity_view_display.paragraph.d_p_side_image.default' => '36085e90252d0487cb0c60c83280199b',
      'paragraphs.paragraphs_type.d_p_side_image' => 'e6cc1ea4ff08ed70cc27dc190211f15f',
    ],
    'd_p_side_tiles' => [
      'core.entity_form_display.paragraph.d_p_side_tiles.default' => '55987245933128f7203534ff12f35de0',
      'core.entity_view_display.paragraph.d_p_side_tiles.default' => 'cc5e369f8f733689f35ed7103969c3f6',
      'paragraphs.paragraphs_type.d_p_side_tiles' => '51701e362646f0dcb3883f11f782601a',
    ],
    'd_p_subscribe_file' => [
      'core.entity_form_display.paragraph.d_p_subscribe_file.default' => 'cda75fb4194deb6136547599542edd91',
      'core.entity_view_display.paragraph.d_p_subscribe_file.default' => 'd7b6b79202744c3489c1efc5d10878c7',
      'paragraphs.paragraphs_type.d_p_subscribe_file' => 'e873f19736da3ded747bb1ba90acaa9f',
    ],
    'd_p_text_blocks' => [
      'core.entity_form_display.paragraph.d_p_group_of_text_blocks.default' => '6349b473b6d4229f3cd7acd75614e3de',
      'core.entity_form_display.paragraph.d_p_single_text_block.default' => 'e66fbddb7ec04560475cf389ac539e75',
      'core.entity_view_display.paragraph.d_p_group_of_text_blocks.default' => 'a105a69391e0f27ab008e62d7f86e32c',
      'core.entity_view_display.paragraph.d_p_single_text_block.default' => 'dea7705821261b011c8bb7c71d0e1128',
      'field.field.paragraph.d_p_group_of_text_blocks.field_d_number' => '4ba9ac76f80d4e632a294975430f98bd',
      'field.field.paragraph.d_p_single_text_block.field_d_cta_link' => 'e56c150543215f50064247d4cf12abff',
      'paragraphs.paragraphs_type.d_p_group_of_text_blocks' => '4e3c989a6f6e10da8e87c4ca326468e5',
      'paragraphs.paragraphs_type.d_p_single_text_block' => 'a18af9bb4ad3860bdedec45fe54949f7',
    ],
    'd_p_text_paged' => [
      'core.entity_form_display.paragraph.d_p_text_paged.default' => '8b931b691255866cc6638ec1966eaea3',
      'core.entity_view_display.paragraph.d_p_text_paged.default' => '0397db2e6d6ed30522f39c36df45fc31',
      'paragraphs.paragraphs_type.d_p_text_paged' => '27ec212324112d0f15b7c3f1ad1505b3',
    ],
    'd_p_text_with_bckg' => [
      'core.entity_form_display.paragraph.d_p_text_with_bckg.default' => '67d2f71ab563ad7380c57fdba47f2d63',
      'core.entity_view_display.paragraph.d_p_text_with_bckg.default' => 'e1464182e4bdb8c7f6fa5c8c18d0d502',
      'paragraphs.paragraphs_type.d_p_text_with_bckg' => 'f480ac5c97dfec4113f6702cb4cd6ae0',
    ],
    'd_p_tiles' => [
      'core.entity_form_display.paragraph.d_p_tiles.default' => 'dbba5191a9b13ef65bee4ca102956a80',
      'core.entity_view_display.paragraph.d_p_tiles.default' => '96616b3236a940249e4f420554893ce0',
    ],
  ];
  $values['droopler__droopler_update_8105_1'] = $updater->importConfigs($configs);

  $module_handler = \Drupal::service('module_handler');
  if ($module_handler->moduleExists('d_blog')) {
    // Update d_blog config.
    $configs = [
      'd_blog' => [
        'core.entity_form_display.node.blog_post.default' => '2cf048fbadcd576c604bc3f403102caa',
        'core.entity_form_display.paragraph.d_p_blog_image.default' => '9af22a1058bd4cf20c3e0f01e8c4674e',
        'core.entity_form_display.taxonomy_term.blog_posts_category.default' => '80050259f04971747c90d8bdc74f959a',
        'core.entity_view_display.node.blog_post.default' => 'c5fe842501a2ae565fc022562ca43704',
        'core.entity_view_display.node.blog_post.teaser' => '8bd7607d55d3ce1a184fc597bb24b18e',
        'core.entity_view_display.node.blog_post.thumbnail' => '2c429f5ac1be793f63fd825b6f673e7f',
        'core.entity_view_display.paragraph.d_p_blog_image.default' => '93fba5911dee499b3445dd056b223ea8',
        'field.field.paragraph.d_p_blog_image.field_d_p_blog_image_full_width' => '44e7518a525650d7fba07a39c0f6525a',
        'field.field.paragraph.d_p_blog_text.field_d_long_text' => '30d7f6455782c675beffff3ced195be8',
        'paragraphs.paragraphs_type.d_p_blog_image' => '324d5e71b1e02bcc3c3294d5f88e6f94',
        'paragraphs.paragraphs_type.d_p_blog_text' => '61152b0f5875e2f77e2600fa3581f880',
      ],
    ];
    $values['droopler__droopler_update_8105_2'] = $updater->importConfigs($configs);
  }
  else {
    $values['droopler__droopler_update_8105_2'] = TRUE;
  }
  if ($module_handler->moduleExists('d_product')) {
    $configs = [
      'd_product' => [
        'core.entity_view_mode.media.d_product_gallery' => 'e6d91a7c6004798c1f0b775638880d20',
        'core.entity_view_mode.media.d_product_image' => '8d6ee31ce888978b7c9631f34a0a2016',
        'core.entity_view_display.node.d_product.default' => 'a0d2d78192365bf94fc77227ca32977b',
        'core.entity_view_display.node.d_product.full' => '75ca2e619110a004551c62017b57ef26',
        'core.entity_view_display.node.d_product.teaser' => '49134caf6f410df190d804b8e45aa6fc',
        'core.entity_form_display.node.d_product.default' => 'e9a571594f7c8d01287e6cb310fde63b',
        'core.entity_view_display.media.d_image.d_product_gallery' => '9cdfa90bad3f20b52b30234dd975db4d',
        'core.entity_view_display.media.d_image.d_product_image' => '0e578ffb82c8481617ebe6db0d092e90',
        'core.entity_view_display.node.d_product.d_small_box' => '75df7a1f59e107eab4f496ff7455bdea',
      ],
    ];
    $values['droopler__droopler_update_8105_3'] = $updater->importConfigs($configs);
  }
  else {
    $values['droopler__droopler_update_8105_3'] = TRUE;
  }

  $progress = [
    'v2.0' => $values,
  ];

  $updater->checklist()->saveProgress($progress);

}

/**
 * Droopler 2.0 beta-1 - update configuration modified since 2.0 alpha-2.
 */
function droopler_update_8106() {
  $updater = \Drupal::service('d_update');
  $module_handler = \Drupal::service('module_handler');

  $configs = [
    'd_media' => [
      'media.type.d_document' => 'override',
      'field.storage.media.field_media_file' => 'override',
      'field.field.media.d_document.field_media_file' => 'override',
      'core.entity_view_mode.media.counter' => 'override',
      'core.entity_view_display.media.d_video.counter' => 'override',
      'core.entity_view_display.media.d_image.counter' => 'override',
      'core.entity_form_display.media.d_document.default' => 'override',
      'core.entity_form_display.media.d_document.media_library' => 'override',
      'core.entity_view_display.media.d_document.default' => 'override',
      'core.entity_view_display.media.d_document.media_library' => 'override',
      'language.content_settings.media.d_document' => 'override',
    ],
    'd_content' => [
      'node.type.content_page' => 'bb51f1046ad8a56afa01acfa5ef550a3',
    ],
    'profile/droopler' => [
      'filter.format.full_html' => 'override',
      'node.settings' => 'override',
    ],
  ];
  if ($module_handler->moduleExists('d_blog')) {
    $configs['d_blog'] = [
      'node.type.blog_post' => 'a697c1000159bc7f4a905c485ce488df',
    ];
  }

  $values['droopler__droopler_update_8106_1'] = $updater->importConfigs($configs);
  $values['droopler__droopler_update_8106_2'] = $updater->updateConfigurations('profile/droopler', 'editor.8106');
  $updater->checklist()->saveProgress(['v2.0' => $values]);
}

/**
 * Droopler 2.0 beta3 add d_block paragraph to some modules, enable d_p_media.
 */
function droopler_update_8107() {
  $modules = ['d_blog', 'd_product'];
  $values['droopler__droopler_update_8107_1'] = update_modules_configuration($modules, '8107');
  if (\Drupal::service('module_handler')->moduleExists('d_p_media')) {
    $values['droopler__droopler_update_8107_2'] = TRUE;
  }
  else {
    $values['droopler__droopler_update_8107_2'] = \Drupal::service('module_installer')->install(['d_p_media'], TRUE);
  }
  \Drupal::service('d_update')
    ->checklist()
    ->saveProgress(['v2.0' => $values]);
}

/**
 * Droopler 2.0 beta-3 - installing SEO modules.
 */
function droopler_update_8108(&$sandbox) {
  // Install SEO contrib modules.
  $updater = \Drupal::service('d_update');
  $module_installer = \Drupal::service('module_installer');
  $module_handler = \Drupal::service('module_handler');
  try {
    $advaggModules = [
      'advagg',
      'advagg_mod',
      'advagg_js_minify',
      'advagg_css_minify',
    ];
    $modules = [
      'page_cache',
      'dynamic_page_cache',
    ];
    $result = $module_installer->install(array_merge($modules, $advaggModules), TRUE);
    $values['droopler__droopler_update_8108_1'] = $result;
  }
  catch (MissingDependencyException $e) {
    $values['droopler__droopler_update_8108_1'] = FALSE;
  }
  // Import seo configs.
  $configs = [];
  foreach ($advaggModules as $advaggModule) {
    if ($module_handler->moduleExists($advaggModule)) {
      $configs[$advaggModule] = [$advaggModule . 'settings'];
    }
  }

  $values['droopler__droopler_update_8108_2'] = $updater->importConfigs($configs);
  $updater->checklist()->saveProgress(['v2.0' => $values]);
}

/**
 * Droopler 2.0 beta-3 turn on new modules.
 */
function droopler_update_8109() {
  if (\Drupal::service('module_handler')->moduleExists('d_block')) {
    $values['droopler__droopler_update_8109_1'] = TRUE;
  }
  else {
    $values['droopler__droopler_update_8109_1'] = \Drupal::service('module_installer')->install(['d_block'], TRUE);
  }
  \Drupal::service('d_update')
    ->checklist()
    ->saveProgress(['v2.0' => $values]);
}

/**
 * Droopler 2.0 beta3 add d_p_counters paragraph view_mode counter.
 */
function droopler_update_8110() {
  $values['droopler__droopler_update_8110_1'] = update_modules_configuration(['d_p_counters'], '8110');
  \Drupal::service('d_update')
    ->checklist()
    ->saveProgress(['v2.0' => $values]);
}

/**
 * Droopler 2.1 install SVG Image Responsive.
 */
function droopler_update_8111() {
  $values['droopler__droopler_update_8111_1'] = \Drupal::service('module_installer')->install(['svg_image_responsive'], TRUE);
  \Drupal::service('d_update')
    ->checklist()
    ->saveProgress(['v2.1' => $values]);
}

/**
 * Droopler 2.1 update droopler_theme configuration.
 */
function droopler_update_8112() {
  $updater = \Drupal::service('d_update');

  $values['droopler__droopler_update_8112_1'] = $updater->updateConfigurations('profile/droopler', 'droopler_theme.8112');

  $updater->checklist()
    ->saveProgress(['v2.1' => $values]);
}

/**
 * Droopler 2.1 update d_product configuration.
 */
function droopler_update_8113() {
  $updater = \Drupal::service('d_update');

  $configs = [
    'd_product' => [
      'image.style.product_main_image' => 'override',
      'image.style.product_navigation_image' => 'override',
      'image.style.product_thumbnail_pc' => 'override',
    ],
  ];

  $values['droopler__droopler_update_8113_1'] = $updater->importConfigs($configs);
  $values['droopler__droopler_update_8113_2'] = update_modules_configuration(['d_product'], '8113');

  $updater->checklist()
    ->saveProgress(['v2.1' => $values]);
}

/**
 * Droopler 2.1 grant view media permission to authenticated users.
 */
function droopler_update_8114() {
  $permission = 'view media';

  $role = Role::load('authenticated');
  $role->grantPermission($permission)
    ->save();

  $values['droopler__droopler_update_8114_1'] = $role->hasPermission($permission);

  Drupal::service('d_update')
    ->checklist()
    ->saveProgress(['v2.1' => $values]);
}

/**
 * Droopler 2.2 - add missing common fields (CTA, Icon, Long text).
 */
function droopler_update_8115() {
  /** @var Drupal\d_update\Updater $updater */
  $updater = \Drupal::service('d_update');

  $configs = [
    'd_p_carousel' => [
      'field.field.paragraph.d_p_carousel.field_d_cta_link' => '',
    ],
    'd_p_gallery' => [
      'field.field.paragraph.d_p_gallery.field_d_cta_link' => '',
    ],
    'd_p_counters' => [
      'field.field.paragraph.d_p_group_of_counters.field_d_cta_link' => '',
      'field.field.paragraph.d_p_group_of_counters.field_d_long_text' => '',
      'field.field.paragraph.d_p_single_counter.field_d_media_icon' => '',
    ],
    'd_p_side_by_side' => [
      'field.field.paragraph.d_p_side_by_side.field_d_cta_link' => '',
      'field.field.paragraph.d_p_side_by_side.field_d_media_icon' => '',
    ],
    'd_p_tiles' => [
      'field.field.paragraph.d_p_tiles.field_d_cta_link' => '',
    ],
    'd_p_reference_content' => [
      'field.field.paragraph.d_p_reference_content.field_d_long_text' => '',
      'field.field.paragraph.d_p_reference_content.field_d_media_icon' => '',
    ],
  ];

  $values['droopler__droopler_update_8115_1'] = $updater->importConfigs($configs);
  $values['droopler__droopler_update_8115_2'] = update_modules_configuration(array_keys($configs), '8115');

  $updater->checklist()
    ->saveProgress(['v2.2' => $values]);
}

/**
 * Droopler 2.2 - add Header Layout settings for Content Page node types.
 */
function droopler_update_8116() {
  /** @var Drupal\d_update\Updater $updater */
  $updater = \Drupal::service('d_update');

  $configs = [
    'd_content' => [
      'field.storage.node.field_header_cta' => '',
      'field.storage.node.field_header_layout' => '',
      'field.field.node.content_page.field_header_cta' => '',
      'field.field.node.content_page.field_header_layout' => '',
      'core.entity_view_mode.node.d_header' => '',
      'core.entity_view_display.node.content_page.d_header' => '',
    ],
  ];

  $values['droopler__droopler_update_8116_1'] = $updater->importConfigs($configs);
  $values['droopler__droopler_update_8116_2'] = update_modules_configuration(array_keys($configs), '8116');

  $updater->checklist()
    ->saveProgress(['v2.2' => $values]);
}

/**
 * Droopler 2.2 - add new field for content types for metatag support.
 */
function droopler_update_8117() {
  /** @var Drupal\d_update\Updater $updater */
  $updater = \Drupal::service('d_update');

  $values['droopler__droopler_update_8117_1'] = $updater->importConfigs([
    'd_p' => [
      'field.storage.node.field_meta_tags' => '',
    ],
  ]);

  $configs = [
    'd_blog' => [
      'field.field.node.blog_post.field_meta_tags' => '',
    ],
    'd_product' => [
      'field.field.node.d_product.field_meta_tags' => '',
    ],
    'd_content' => [
      'field.field.node.content_page.field_meta_tags' => '',
    ],
  ];

  $values['droopler__droopler_update_8117_2'] = $updater->importConfigs($configs);
  $values['droopler__droopler_update_8117_3'] = update_modules_configuration(array_keys($configs), '8117');

  $updater->checklist()
    ->saveProgress(['v2.2' => $values]);
}

/**
 * Droopler 2.2 Migrate column count field.
 */
function droopler_update_8118(&$sandbox) {
  $bundles = [
    'd_p_carousel',
    'd_p_group_of_counters',
    'd_p_group_of_text_blocks',
  ];

  if (!isset($sandbox['total'])) {
    $query = \Drupal::entityQuery('paragraph')
      ->condition('type', $bundles, 'IN')
      ->exists('field_d_number')
      ->execute();

    $sandbox['total'] = count($query);
    $sandbox['current'] = 0;
  }

  $paragraphs_per_batch = 25;

  $query = \Drupal::entityQuery('paragraph')
    ->condition('type', $bundles, 'IN')
    ->exists('field_d_number')
    ->range($sandbox['current'], $paragraphs_per_batch)
    ->execute();

  foreach ($query as $pid) {
    $paragraph = \Drupal::entityTypeManager()
      ->getStorage('paragraph')
      ->load($pid);

    /** @var \Drupal\d_p\Plugin\Field\ConfigurationStorageFieldItemListInterface $setting_field */
    $setting_field = ConfigurationStorage::getSettingsFieldFromEntity($paragraph);

    // Migrate column size.
    switch ($paragraph->bundle()) {
      case 'd_p_carousel':
        $items_count = $paragraph->field_d_p_cs_item_reference->count();
        $old_column_count = $paragraph->field_d_number ? ($paragraph->field_d_number->value ?? '2') : '2';
        $tablet_column_count = $old_column_count == '1' ? '1' : '2';

        if ($items_count <= $old_column_count) {
          if ($setting_field->hasClass('slider-desktop-off')) {
            $desktop_column_count = $items_count;
          }
          else {
            $desktop_column_count = $items_count - 1;
          }
        }
        else {
          $desktop_column_count = $old_column_count;
        }
        break;

      default:
        $old_column_count = $paragraph->field_d_number ? ($paragraph->field_d_number->value ?? '3') : '3';
        $tablet_column_count = $old_column_count;
        $desktop_column_count = $old_column_count;
        break;
    }

    $setting_field->setSettingValue(
      ParagraphSettingTypesInterface::COLUMN_COUNT_SETTING_NAME,
      $desktop_column_count
    )->setSettingValue(
      ParagraphSettingTypesInterface::COLUMN_COUNT_TABLET_SETTING_NAME,
      $tablet_column_count
    )->setSettingValue(
      ParagraphSettingTypesInterface::COLUMN_COUNT_MOBILE_SETTING_NAME,
      1
    );

    $paragraph->save();

    $sandbox['current']++;
  }

  \Drupal::messenger()->addMessage($sandbox['current'] . ' paragraphs processed.');
  $sandbox['#finished'] = $sandbox['total'] == 0 ? 1 : $sandbox['current'] / $sandbox['total'];

  if ($sandbox['#finished'] === 1) {
    $modules = [
      'd_p_carousel',
      'd_p_counters',
      'd_p_text_blocks',
    ];
    $values['droopler__droopler_update_8118_1'] = update_modules_configuration($modules, '8118');
    \Drupal::service('d_update')->checklist()
      ->saveProgress(['v2.2' => $values]);

    foreach ($bundles as $bundle) {
      $field = FieldConfig::loadByName('paragraph', $bundle, 'field_d_number');

      if ($field !== NULL) {
        $field->delete();
      }
    }
  }
}

/**
 * Droopler 2.2 update Product configs fixing issues related to revisions.
 */
function droopler_update_8119() {
  /** @var Drupal\d_update\Updater $updater */
  $updater = \Drupal::service('d_update');

  $values['droopler__droopler_update_8119_1'] = update_modules_configuration(['d_product'], '8119');

  $updater->checklist()
    ->saveProgress(['v2.2' => $values]);
}

/**
 * Droopler 2.2 fix missing dependency and features changes.
 */
function droopler_update_8120() {
  /** @var Drupal\d_update\Updater $updater */
  $updater = \Drupal::service('d_update');

  $bundles = [
    'd_blog',
    'd_media',
    'd_p_banner',
    'd_p_carousel',
    'd_p_counters',
    'd_p_form',
    'd_p_gallery',
    'd_p_media',
    'd_p_node',
    'd_p_reference_content',
    'd_p_side_by_side',
    'd_p_side_embed',
    'd_p_side_image',
    'd_p_side_tiles',
    'd_p_subscribe_file',
    'd_p_text_blocks',
    'd_p_text_paged',
    'd_p_text_with_bckg',
    'd_p_tiles',
    'd_product',
  ];

  $values['droopler__droopler_update_8120_1'] = update_modules_configuration($bundles, '8120');

  $updater->checklist()
    ->saveProgress(['v2.2' => $values]);
}

/**
 * Droopler 2.2 improve Blog Post "teaser small" image style.
 */
function droopler_update_8121() {
  /** @var Drupal\d_update\Updater $updater */
  $updater = \Drupal::service('d_update');

  $configs = [
    'd_media' => [
      'image.style.large_gallery_thumbnail' => '',
    ],
  ];

  $values['droopler__droopler_update_8121_1'] = $updater->importConfigs($configs);
  $values['droopler__droopler_update_8121_2'] = update_modules_configuration(['d_blog'], '8121');

  $updater->checklist()
    ->saveProgress(['v2.2' => $values]);
}

/**
 * Droopler 2.2 configure meta tags for Commerce products.
 */
function droopler_update_8122() {
  /** @var Drupal\d_update\Updater $updater */
  $updater = \Drupal::service('d_update');

  if (\Drupal::service('module_handler')->moduleExists('d_commerce_product')) {
    try {
      \Drupal::service('module_installer')->install(['metatag_open_graph_products']);
      $configs = [
        'd_commerce_product' => [
          'metatag.metatag_defaults.commerce_product.yml' => '',
        ],
      ];
      $values['droopler__droopler_update_8122_1'] = $updater->importConfigs($configs);
    }
    catch (MissingDependencyException $e) {
      $values['droopler__droopler_update_8122_1'] = FALSE;
    }
  }
  else {
    $values['droopler__droopler_update_8122_1'] = TRUE;
  }

  $updater->checklist()
    ->saveProgress(['v2.2' => $values]);
}

/**
 * Droopler 2.2 Migrate paddings modifiers.
 */
function droopler_update_8123(&$sandbox) {
  $entity_ids = [
    'd_p_side_by_side',
    'd_p_group_of_text_blocks',
    'd_p_carousel',
    'd_p_text_paged',
    'd_p_reference_content',
  ];

  if (!isset($sandbox['total'])) {
    $query = \Drupal::entityQuery('paragraph');
    $group = $query->orConditionGroup();

    foreach ($entity_ids as $entity_id) {
      $group->condition('type', $entity_id);
    }

    $query = $query->condition($group)->execute();

    $sandbox['total'] = count($query);
    $sandbox['current'] = 0;
    $sandbox['changed'] = 0;
  }

  $paragraphs_per_batch = 25;

  $query = \Drupal::entityQuery('paragraph');
  $group = $query->orConditionGroup();

  foreach ($entity_ids as $entity_id) {
    $group->condition('type', $entity_id);
  }

  $query = $query
    ->condition($group)
    ->range($sandbox['current'], $paragraphs_per_batch)
    ->execute();

  foreach ($query as $pid) {
    $paragraph = \Drupal::entityTypeManager()
      ->getStorage('paragraph')
      ->load($pid);

    $replaces = [
      'no-padding-bottom' => 'padding-bottom-none',
      'no-padding-top' => 'padding-top-none',
    ];

    /** @var \Drupal\d_p\Plugin\Field\ConfigurationStorageFieldItemListInterface $setting_field */
    $setting_field = ConfigurationStorage::getSettingsFieldFromEntity($paragraph);

    foreach ($replaces as $old => $new) {
      $setting_field->replaceClass($old, $new);
    }

    $paragraph->save();

    $sandbox['changed']++;
    $sandbox['current']++;
  }

  $sandbox['#finished'] = $sandbox['total'] == 0 ? 1 : $sandbox['current'] / $sandbox['total'];

  if ($sandbox['#finished'] === 1) {
    $values['droopler__droopler_update_8123_1'] = TRUE;
    \Drupal::service('d_update')->checklist()
      ->saveProgress(['v2.2' => $values]);
    \Drupal::messenger()->addMessage($sandbox['current'] . ' paragraphs processed, ' . $sandbox['changed'] . ' changed.');
  }
}

/**
 * Droopler 2.2 update Linkit.
 */
function droopler_update_8124() {
  /** @var Drupal\d_update\Updater $updater */
  $updater = \Drupal::service('d_update');

  $values['droopler__droopler_update_8124_1'] = $updater->updateConfigurations('profile/droopler', 'editor.8124');

  $updater->checklist()
    ->saveProgress(['v2.2' => $values]);
}

/**
 * Droopler 2.2 - remove spacing from CTA field in Reference Content Paragraph.
 */
function droopler_update_8125() {
  /** @var Drupal\d_update\Updater $updater */
  $updater = \Drupal::service('d_update');

  $values['droopler__droopler_update_8125_1'] = update_modules_configuration(['d_p_reference_content'], '8125');
  $updater->checklist()->saveProgress(['v2.2' => $values]);
}

/**
 * Droopler 2.2 - remove "mt-5" spacing from CTA field saved in database.
 */
function droopler_update_8126(&$sandbox) {
  /** @var Drupal\d_update\Updater $updater */
  $updater = \Drupal::service('d_update');
  $limit = 25;
  if (!isset($sandbox['current'])) {
    $sandbox['current'] = 0;
  }
  $entities = \Drupal::entityQuery('paragraph')
    ->condition('type', 'd_p_reference_content')
    ->range($sandbox['current'], $limit)
    ->execute();
  $sandbox['total'] = count($entities);
  foreach ($entities as $entity_id) {
    $entity = \Drupal::entityTypeManager()->getStorage('paragraph')->load($entity_id);
    if ($entity->hasField('field_d_cta_link')) {
      $fields = $entity->get('field_d_cta_link');
      foreach ($fields as $field) {
        $value = $field->getValue();
        // Check if field has a class 'mt-5'. If so, we remove it.
        $key = array_search('mt-5', $value['options']['attributes']['class']);
        if ($key !== FALSE) {
          unset($value['options']['attributes']['class'][$key]);
          $field->setValue($value);
          $entity->save();
        }
      }
    }
    $sandbox['current']++;
  }
  $sandbox['#finished'] = empty($sandbox['total']) ? 1 : ($sandbox['current'] / ($sandbox['total'] + $sandbox['current']));
  if ($sandbox['#finished'] === 1) {
    $updater->checklist()->saveProgress(['v2.2' => ['droopler__droopler_update_8126_1' => TRUE]]);
  }

}

/**
 * Droopler 2.2 Migrate Paragraphs Settings values to the new format.
 */
function droopler_update_8127(&$sandbox) {
  if (!isset($sandbox['total'])) {
    $sandbox['total'] = \Drupal::entityQuery('paragraph')
      ->exists('field_d_settings')
      ->count()->execute();

    $sandbox['current'] = 0;
  }

  $paragraphs_per_batch = 10;

  $paragraphs_ids = \Drupal::entityQuery('paragraph')
    ->exists('field_d_settings')
    ->range($sandbox['current'], $paragraphs_per_batch)
    ->execute();

  $paragraphs = [];
  if (!empty($paragraphs_ids)) {
    $paragraphs = \Drupal::entityTypeManager()
      ->getStorage('paragraph')
      ->loadMultiple($paragraphs_ids);
  }

  foreach ($paragraphs as $paragraph) {
    $sandbox['current']++;
    /** @var \Drupal\d_p\Plugin\Field\ConfigurationStorageFieldItemListInterface $setting_field */
    $setting_field = ConfigurationStorage::getSettingsFieldFromEntity($paragraph);

    // Always replace background gray light 2 class.
    $setting_field->replaceClass('background-gray-light-2', 'theme-gray');

    $theme_classes = [
      'theme-default',
      'theme-primary',
      'theme-secondary',
      'theme-gray',
    ];

    if ($setting_field->hasClass($theme_classes)) {
      $setting_field
        ->removeClass('theme-invert')
        ->removeClass('background-gray-light-2');

      $paragraph->save();
      continue;
    }

    if ($setting_field->hasClass('theme-invert')) {
      // Migrate theme-invert.
      switch ($paragraph->bundle()) {
        case 'd_p_side_embed':
        case 'd_p_side_image':
        case 'd_p_side_tiles':
          if ($paragraph->hasField('field_d_background_color')) {
            $background = $paragraph->field_d_background_color->value;
            if (in_array($background, ['#e4e4e4', '#dddddd'])) {
              $setting_field->replaceClass('theme-invert', 'theme-gray');
              break;
            }
          }
          $setting_field->replaceClass('theme-invert', 'theme-secondary');

          break;

        case 'd_p_text_paged':
        case 'd_p_group_of_text_blocks':
          $setting_field->replaceClass('theme-invert', 'theme-primary');
          break;

        default:
          $setting_field->replaceClass('theme-invert', 'theme-default');
          break;
      }
    }
    else {
      $setting_field->addClass('theme-default');
    }

    $paragraph->save();
  }

  \Drupal::messenger()->addMessage($sandbox['current'] . ' paragraphs processed (total ' . $sandbox['total'] . ').');
  $sandbox['#finished'] = $sandbox['total'] == 0 ? 1 : $sandbox['current'] / $sandbox['total'];

  if ($sandbox['#finished'] === 1) {
    $values['droopler__droopler_update_8127_1'] = TRUE;
    \Drupal::service('d_update')->checklist()->saveProgress(['v2.2' => $values]);
  }

}

/**
 * Droopler 2.2 Paragraph UI improvements and unification.
 */
function droopler_update_8128(&$sandbox) {
  /** @var Drupal\d_update\Updater $updater */
  $updater = \Drupal::service('d_update');

  $bundles = [
    'd_block',
    'd_p_reference_content',
    'd_p_banner',
    'd_p_carousel',
    'd_p_counters',
    'd_p_form',
    'd_p_gallery',
    'd_p_side_by_side',
    'd_p_side_embed',
    'd_p_side_image',
    'd_p_side_tiles',
    'd_p_subscribe_file',
    'd_p_text_blocks',
    'd_p_text_paged',
    'd_p_text_with_bckg',
    'd_p_tiles',
  ];

  $values['droopler__droopler_update_8128_1'] = update_modules_configuration($bundles, '8128');
  $updater->checklist()->saveProgress(['v2.2' => $values]);
}

/**
 * Droopler 2.2 Migrate background color.
 */
function droopler_update_8129(&$sandbox) {
  if (!isset($sandbox['total'])) {
    $sandbox['total'] = \Drupal::entityQuery('paragraph')
      ->exists('field_d_background_color')
      ->count()->execute();

    $sandbox['current'] = 0;
  }

  $paragraphs_per_batch = 25;

  $query = \Drupal::entityQuery('paragraph')
    ->exists('field_d_background_color')
    ->range($sandbox['current'], $paragraphs_per_batch)
    ->execute();

  foreach ($query as $pid) {
    $paragraph = \Drupal::entityTypeManager()
      ->getStorage('paragraph')
      ->load($pid);

    /** @var \Drupal\d_p\Plugin\Field\ConfigurationStorageFieldItemListInterface $settings_field */
    $settings_field = ConfigurationStorage::getSettingsFieldFromEntity($paragraph);
    $classes = $settings_field->getClasses();
    $background_color = $paragraph->field_d_background_color->value;
    if (!empty($background_color)) {
      switch ($background_color) {
        case '#ac0000':
          $class = 'theme-primary';
          break;

        case '#e4e4e4':
        case '#dddddd':
          $class = 'theme-gray';
          break;

        case '#ffffff':
        case '#fff':
          $class = 'theme-secondary';
          break;

        default:
          $class = 'theme-custom';
          $black = '#000000';
          $white = '#ffffff';
          $background_color_hex = str_replace('#', '', $background_color);

          /*
           * HSL algorithm.
           * @see https://stackoverflow.com/a/12228730
           */
          $lightness = function ($hex) {
            $r = hexdec($hex[0] . $hex[1]);
            $g = hexdec($hex[2] . $hex[3]);
            $b = hexdec($hex[4] . $hex[5]);

            return (max($r, $g, $b) + min($r, $g, $b)) / 510.0;
          };

          $settings_field->setSettingValue(ParagraphSettingTypesInterface::THEME_COLORS_SETTING_NAME, [
            'background' => $background_color,
            'text' => $lightness($background_color_hex) <= 0.6 ? $white : $black,
          ]);
      }
    }
    else {
      $class = 'theme-default';
    }

    $classes = preg_replace('/theme-([a-z]*)/', $class, $classes);
    if (array_search($class, $classes) === FALSE) {
      $classes[] = $class;
    }
    $settings_field->setClasses($classes);

    $paragraph->save();

    $sandbox['current']++;
  }

  \Drupal::messenger()
    ->addMessage($sandbox['current'] . ' paragraphs processed.');
  $sandbox['#finished'] = $sandbox['total'] == 0 ? 1 : $sandbox['current'] / $sandbox['total'];

  if ($sandbox['#finished'] === 1) {
    $modules = [
      'd_p_side_image',
      'd_p_text_blocks',
    ];
    $values['droopler__droopler_update_8129_1'] = update_modules_configuration($modules, '8129');

    $bundles = [
      'd_p_side_image',
      'd_p_single_text_block',
    ];
    foreach ($bundles as $bundle) {
      $field = FieldConfig::loadByName('paragraph', $bundle, 'field_d_background_color');

      if ($field !== NULL) {
        $field->delete();
      }
    }

    $values['droopler__droopler_update_8129_2'] = \Drupal::service('module_installer')
      ->install(['d_color'], TRUE);

    \Drupal::service('d_update')->checklist()
      ->saveProgress(['v2.2' => $values]);
  }
}

/**
 * Droopler 2.2 update configs for featured view mode in media.
 */
function droopler_update_8130() {
  /** @var Drupal\d_update\Updater $updater */
  $updater = \Drupal::service('d_update');

  $configs = [
    'd_media' => [
      'core.entity_view_mode.media.tiles_gallery_fullscreen_featured' => '',
      'core.entity_view_display.media.d_image.tiles_gallery_fullscreen_featured' => '',
    ],
  ];

  $values['droopler__droopler_update_8130_1'] = $updater->importConfigs($configs);

  $updater->checklist()
    ->saveProgress(['v2.2' => $values]);
}

/**
 * Droopler 2.2 Migrate layout settings.
 */
function droopler_update_8131(&$sandbox) {

  $bundles = [
    'd_p_tiles',
    'd_p_side_tiles',
    'd_p_side_image',
    'd_p_side_embed',
    'd_p_form',
  ];
  $paragraphs_per_batch = 25;
  if (!isset($sandbox['current'])) {
    $sandbox['current'] = 0;
  }

  $paragraphs_ids = \Drupal::entityQuery('paragraph')
    ->condition('type', $bundles, 'IN')
    ->range($sandbox['current'], $paragraphs_per_batch)
    ->execute();

  foreach ($paragraphs_ids as $id) {
    $paragraph = \Drupal::entityTypeManager()
      ->getStorage('paragraph')
      ->load($id);

    /** @var \Drupal\d_p\Plugin\Field\ConfigurationStorageFieldItemListInterface $setting_field */
    $setting_field = ConfigurationStorage::getSettingsFieldFromEntity($paragraph);

    switch ($paragraph->bundle()) {
      case 'd_p_side_image':
        if ($paragraph->hasField('field_d_p_si_image_side')) {
          $side_image_layout = $paragraph->get('field_d_p_si_image_side') ? $paragraph->get('field_d_p_si_image_side')->value : 'left';
          $setting_field->setSettingValue(ParagraphSettingTypesInterface::PARAGRAPH_SETTING_SIDE_IMAGE_LAYOUT, $side_image_layout);
        }
        break;

      case 'd_p_side_embed':
        if ($paragraph->hasField('field_d_p_si_image_side')) {
          $embed_layout = $paragraph->get('field_d_p_si_image_side') ? $paragraph->get('field_d_p_si_image_side')->value : 'left';
          $setting_field->setSettingValue(ParagraphSettingTypesInterface::PARAGRAPH_SETTING_EMBED_LAYOUT, $embed_layout);
        }
        break;

      case 'd_p_form':
        if ($paragraph->hasField('field_d_layout_modifier')) {
          $form_layout = $paragraph->get('field_d_layout_modifier') ? $paragraph->get('field_d_layout_modifier')->value : 'left';
          $setting_field->setSettingValue(ParagraphSettingTypesInterface::PARAGRAPH_SETTING_FORM_LAYOUT, $form_layout);
        }
        break;

      case 'd_p_side_tiles':
        if ($paragraph->hasField('field_d_p_si_image_side')) {
          $side_tiles_layout = $paragraph->get('field_d_p_si_image_side') ? $paragraph->get('field_d_p_si_image_side')->value : 'left';
          $setting_field->setSettingValue(ParagraphSettingTypesInterface::PARAGRAPH_SETTING_SIDE_TILES_LAYOUT, $side_tiles_layout);
        }
        break;

      case 'd_p_tiles':
        $featured_images = [];
        // Migrate features images.
        if ($paragraph->hasField('field_d_media_image')) {
          $items = $paragraph->get('field_d_media_image')
            ->referencedEntities();
          foreach ($items as $key => $item) {
            if ($item->hasField('field_media_image') && $image = $item->get('field_media_image')
              ->first()) {
              $alt = $image->get('alt')->getString();
              if (strstr($alt, '2x2')) {
                $image->set('alt', trim(str_replace('2x2', '', $alt)));
                $item->save();
                $featured_images[] = $key + 1;
              }
            }
          }
        }
        if (!empty($featured_images)) {
          $featured_images_value = implode(",", $featured_images);
          $setting_field->setSettingValue(ParagraphSettingTypesInterface::PARAGRAPH_FEATURED_IMAGES, $featured_images_value);
        }
        break;
    }

    $paragraph->save();

    $sandbox['current']++;
  }

  $sandbox['#finished'] = empty($paragraphs_ids) ? 1 : $sandbox['current'] / (count($paragraphs_ids) + $sandbox['current']);

  if ($sandbox['#finished'] === 1) {
    // Remove fields from database.
    foreach ($bundles as $bundle) {
      $field = $bundle == 'd_p_form' ? 'field_d_layout_modifier' : 'field_d_p_si_image_side';
      $field = FieldConfig::loadByName('paragraph', $bundle, $field);
      if ($field !== NULL) {
        $field->delete();
      }
    }
    $values['droopler__droopler_update_8131_1'] = update_modules_configuration([
      'd_p_banner',
      'd_p_side_tiles',
      'd_p_side_image',
      'd_p_side_embed',
      'd_p_form',
    ], '8131');
    \Drupal::service('d_update')->checklist()
      ->saveProgress(['v2.2' => $values]);
    \Drupal::messenger()->addMessage($sandbox['current'] . ' paragraphs processed.');
  }
}

/**
 * Droopler 2.2 Add settings widget configuration.
 */
function droopler_update_8132(&$sandbox) {
  $values['droopler__droopler_update_8132_1'] = update_modules_configuration([
    'd_block',
    'd_p_banner',
    'd_p_carousel',
    'd_p_counters',
    'd_p_form',
    'd_p_gallery',
    'd_p_reference_content',
    'd_p_side_by_side',
    'd_p_side_embed',
    'd_p_side_image',
    'd_p_side_tiles',
    'd_p_subscribe_file',
    'd_p_text_blocks',
    'd_p_text_paged',
    'd_p_text_with_bckg',
    'd_p_tiles',
  ], '8132');

  \Drupal::service('d_update')->checklist()
    ->saveProgress(['v2.2' => $values]);
}

/**
 * Droopler 3.0 Add settings widget to d_p_node.
 */
function droopler_update_8133(&$sandbox) {
  /** @var Drupal\d_update\Updater $updater */
  $updater = \Drupal::service('d_update');

  $configs = [
    'd_p_node' => [
      'field.field.paragraph.d_p_node.field_d_settings' => '',
    ],
  ];

  $values['droopler__droopler_update_8133_1'] = $updater->importConfigs($configs);
  $values['droopler__droopler_update_8133_2'] = update_modules_configuration([
    'd_p_node',
  ], '8133');

  $updater->checklist()
    ->saveProgress(['v3.0' => $values]);
}

/**
 * Droopler 3.1 grant access contextual links permission to editor users.
 */
function droopler_update_8134() {
  $permission = 'access contextual links';

  if ($role = Role::load('d_editor')) {
    $role->grantPermission($permission)->save();
    $values['droopler__droopler_update_8134_1'] = $role->hasPermission($permission);
  }

  Drupal::service('d_update')
    ->checklist()
    ->saveProgress(['v3.1' => $values]);
}

/**
 * Droopler 3.1 Add settings widget to the "d_p_side_by_side" module.
 */
function droopler_update_8135(&$sandbox) {
  $values['droopler__droopler_update_8135_1'] = update_modules_configuration([
    'd_p_side_by_side',
  ], '8135');

  \Drupal::service('d_update')->checklist()
    ->saveProgress(['v3.1' => $values]);
}

/**
 * Droopler 3.1 Update CTA widget to the "d_p_carousel" module.
 */
function droopler_update_8136(&$sandbox) {
  $values['droopler__droopler_update_8136_1'] = update_modules_configuration([
    'd_p_carousel',
  ], '8136');

  \Drupal::service('d_update')->checklist()
    ->saveProgress(['v3.1' => $values]);
}

/**
 * Droopler 3.1 Changing CTA widget settings configuration.
 */
function droopler_update_8137(&$sandbox) {
  $values['droopler__droopler_update_8137_1'] = update_modules_configuration([
    'd_p_counters',
    'd_p_gallery',
    'd_p_side_by_side',
    'd_p_side_image',
    'd_p_side_tiles',
    'd_p_text_blocks',
    'd_p_text_paged',
    'd_p_text_with_bckg',
  ], '8137');

  \Drupal::service('d_update')->checklist()
    ->saveProgress(['v3.1' => $values]);
}

/**
 * Droopler 3.1 Updating d_p_tiles and d_p_side_tiles paragraph field grouping.
 */
function droopler_update_8138(&$sandbox) {
  $values['droopler__droopler_update_8138_1'] = update_modules_configuration([
    'd_p_tiles',
    'd_p_side_tiles',
  ], '8138');

  \Drupal::service('d_update')->checklist()
    ->saveProgress(['v3.1' => $values]);
}

/**
 * Droopler 3.3 Change AdvAgg JS minifier from JSqueeze to JShrink.
 */
function droopler_update_8139(&$sandbox) {
  /** @var Drupal\d_update\Updater $updater */
  $updater = \Drupal::service('d_update');
  $updater->updateConfigurations('profile/droopler', 'advagg.8139');
}

/**
 * Droopler PreReq 3.4 - Uninstall and remove the AdvAgg module.
 */
function droopler_update_8140() {
  $module_installer = \Drupal::service('module_installer');

  $values['droopler__droopler_update_8140_1'] = $module_installer
    ->uninstall([
      'advagg',
      'advagg_css_minify',
      'advagg_js_minify',
      'advagg_mod',
      'system_status',
    ], TRUE);

  $values['droopler__droopler_update_8140_2'] = $module_installer
    ->install(['entity'], TRUE);

  \Drupal::service('d_update')->checklist()
    ->saveProgress(['v3.4' => $values]);

  drupal_flush_all_caches();
}
