<?php

/**
 * @file
 * Install and uninstall functions for the WxT installation profile.
 *
 * Leveraged from code provided by Acquia for the Lightning distribution.
 */

use Drupal\node\Entity\NodeType;
use Drupal\workflows\Entity\Workflow;
use Drupal\wxt_core\ConfigHelper as Config;
use Symfony\Component\Yaml\Yaml;

/**
 * Implements hook_requirements().
 */
function wxt_core_requirements($phase) {
  $requirements = [];

  if ($phase === 'install') {
    $info = Drupal::service('extension.list.profile')
      ->get('wxt')
      ->getPathname();

    if (strstr(file_get_contents($info), '# Information added by Drupal.org packaging script')) {
      $requirements['wxt_reject_tarball'] = [
        'title' => t('Missing Composer dependencies'),
        'severity' => REQUIREMENT_ERROR,
        'description' => t('WxT appears to have been downloaded as an archive from drupal.org. WxT cannot be installed this way because drupal.org does not package all the necessary dependencies. Please visit <a href="https://drupalwxt.github.io">this GitHub repository</a> for instructions on how to build WxT using Composer.'),
      ];
    }
  }

  $profile = Drupal::installProfile();
  if (!is_null($profile)) {
    $profile = Drupal::service('extension.list.profile')->get($profile);

    if (isset($profile->info['base profile'])) {
      $requirements['wxt_core_base_profile'] = [
        'title' => t('Base profile'),
        'value' => $profile->info['base profile'],
      ];
    }
  }

  return $requirements;
}

/**
 * Implements hook_install().
 */
function wxt_core_install() {
  // Don't do anything during config sync.
  if (\Drupal::isConfigSyncing()) {
    return;
  }

  // Record all module version numbers, including our own, in config.
  $modules = array_keys(\Drupal::moduleHandler()->getModuleList());
  array_push($modules, 'wxt_core');
  wxt_core_modules_installed($modules);

  $storage = Drupal::entityTypeManager()->getStorage('entity_view_mode');
  $view_modes = $storage->loadMultiple([
    'node.rss',
    'node.search_index',
  ]);
  /** @var \Drupal\Core\Entity\EntityViewModeInterface $view_mode */
  foreach ($view_modes as $view_mode) {
    $view_mode->setThirdPartySetting('wxt_core', 'internal', TRUE);
    $storage->save($view_mode);
  }
}

/**
 * Updates for the WxT 4.0.0 release.
 */
function wxt_core_update_8403() {
  /** @var \Drupal\Core\Extension\ModuleInstallerInterface $module_installer */
  $module_installer = \Drupal::service('module_installer');
  $modules_to_check = [
    'libraries' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('libraries') >= 0) ? TRUE : FALSE,
    'lightning' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning') >= 0) ? TRUE : FALSE,
    'lightning_install' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_install') >= 0) ? TRUE : FALSE,
    'wxt_ext_translation' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('wxt_ext_translation') >= 0) ? TRUE : FALSE,
  ];

  $needs_uninstalling = FALSE;
  $modules_to_uninstall = [];
  $uninstalled = TRUE;

  foreach ($modules_to_check as $module => $installed) {
    if ($installed) {
      $needs_uninstalling = TRUE;
      $modules_to_uninstall[] = $module;
    }
  }

  if ($needs_uninstalling) {
    $uninstalled = $module_installer->uninstall($modules_to_uninstall);
  }

  if ($needs_uninstalling && !$uninstalled) {
    \Drupal::configFactory()
      ->getEditable('core.extension')
      ->clear('module.libraries')
      ->clear('module.lightning')
      ->clear('module.lightning_install')
      ->clear('module.wxt_ext_translation')
      ->save();
    Drupal::keyValue('system.schema')->deleteMultiple([
      'libraries',
      'lightning',
      'lightning_install',
      'wxt_ext_translation',
    ]);
  }

  // Deprecate RDF additions.
  \Drupal::configFactory()->getEditable('rdf.mapping.comment.comment.yml')->delete();
  \Drupal::configFactory()->getEditable('rdf.mapping.node.page.yml')->delete();

  // Deprecate Panels Welcome page.
  \Drupal::configFactory()->getEditable('page_manager.page.welcome.yml')->delete();
  \Drupal::configFactory()->getEditable('page_manager.page_variant.welcome.yml')->delete();

  $module_installer->install([
    'wxt_ext_blocks',
    'wxt_ext_comment',
    'wxt_ext_media',
    'wxt_translation',
  ]);

  // Resolve block_content workflow issue.
  $block_content = [];
  foreach (Workflow::loadMultipleByType('content_moderation') as $workflow) {
    if ($block_moderation = $workflow->getTypePlugin()->getBundlesForEntityType('block_content')) {
      $block_content[] = $block_moderation;
    }
  }

  // Resolve issues with Lightning Scheduler.
  $entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  $modules = [
    'crop',
    'entity_subqueue',
    'media',
  ];
  if (empty($block_content)) {
    $modules[] = 'block_content';
  }
  $fields = [
    'scheduled_transition_date',
    'scheduled_transition_state',
  ];
  foreach ($modules as $module) {
    foreach ($fields as $field) {
      if ($field_storage_definition = $entity_definition_update_manager->getFieldStorageDefinition($field, $module)) {
        $entity_definition_update_manager->uninstallFieldStorageDefinition($field_storage_definition);
      }
    }
  }

  // Panels Title logic adjustments.
  /** @var \Drupal\block\Entity\Block $block */
  foreach (\Drupal::entityTypeManager()->getStorage('block')->loadMultiple() as $block) {
    if ($block->id() !== NULL) {
      $visiblity_conditions = $block->getVisibilityConditions();
      $visibility_rules = $visiblity_conditions->getConfiguration();
      foreach ($visibility_rules as $k => $v) {
        if ($v['id'] == 'panels_title') {
          if (isset($v['enabled']) && $v['enabled'] == 1) {
            unset($visibility_rules[$k]['enabled']);
            $visibility_rules[$k] += [
              'is_panelized' => [
                'enabled' => 1,
              ],
            ];
            $visibility_rules[$k]['negate'] = 1;
          }
          elseif (isset($v['enabled']) && $v['enabled'] == 0) {
            unset($visibility_rules[$k]);
          }
        }
      }
      $visiblity_conditions->setConfiguration($visibility_rules);
      $block->save();
    }
  }

}

/**
 * Updates for the WxT 4.1.0 release.
 */
function wxt_core_update_8410() {
  /** @var \Drupal\Core\Extension\ModuleInstallerInterface $module_installer */
  $module_installer = \Drupal::service('module_installer');
  $modules_to_check = [
    'panelizer' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('panelizer') >= 0) ? TRUE : FALSE,
  ];

  $needs_uninstalling = FALSE;
  $modules_to_uninstall = [];
  $uninstalled = TRUE;

  foreach ($modules_to_check as $module => $installed) {
    if ($installed) {
      $needs_uninstalling = TRUE;
      $modules_to_uninstall[] = $module;
    }
  }

  if ($needs_uninstalling) {
    $uninstalled = $module_installer->uninstall($modules_to_uninstall);
  }

  if ($needs_uninstalling && !$uninstalled) {
    \Drupal::configFactory()
      ->getEditable('core.extension')
      ->clear('module.panelizer')
      ->save();
    \Drupal::keyValue('system.schema')->deleteMultiple([
      'panelizer',
    ]);
  }
}

/**
 * Updates for the WxT 4.3.1 release.
 */
function wxt_core_update_8431() {
  // Don't run if the site isn't using lightning_layout.
  $module_handler = \Drupal::service('module_handler');
  if (!$module_handler->moduleExists('lightning_layout') && !$module_handler->moduleExists('wxt_ext_layout')) {
    return;
  }

  // Retrieve the config factory.
  $config_factory = \Drupal::configFactory();

  // Map lightning_layout.settings to wxt_ext_layout.settings.
  $source = $config_factory->getEditable('lightning_layout.settings');
  $entity_blocks = $source->get('entity_blocks');
  $config_factory->getEditable('wxt_ext_layout.settings')
    ->set('entity_blocks', $entity_blocks)
    ->save();

  // Map third_party_setting lightning_workflow to wxt_ext_workflow.
  $entityTypeManager = \Drupal::service('entity_type.manager');
  $node_types = $entityTypeManager->getStorage('node_type')->loadMultiple();
  foreach ($node_types as $node_type) {
    $node_type_exists = NodeType::load($node_type->id());
    if ($node_type_exists) {
      $third_party_setting = NodeType::load($node_type->id())->getThirdPartySetting('lightning_workflow', 'workflow');
      if ($third_party_setting) {
        NodeType::load($node_type->id())
          ->unsetThirdPartySetting('lightning_workflow', 'workflow')
          ->setThirdPartySetting('wxt_ext_workflow', 'workflow', $third_party_setting)
          ->save();
      }
    }
  }

  // Fully uninstall Lightning Layout.
  /** @var \Drupal\Core\Extension\ModuleInstallerInterface $module_installer */
  $module_installer = \Drupal::service('module_installer');
  $modules_to_check = [
    'lightning_layout' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_layout') >= 0) ? TRUE : FALSE,
    'lightning_banner_block' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_banner_block') >= 0) ? TRUE : FALSE,
    'lightning_landing_page' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_landing_page') >= 0) ? TRUE : FALSE,
    'lightning_map_block' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_map_block') >= 0) ? TRUE : FALSE,
  ];

  $needs_uninstalling = FALSE;
  $modules_to_uninstall = [];
  $uninstalled = TRUE;

  foreach ($modules_to_check as $module => $installed) {
    if ($installed) {
      $needs_uninstalling = TRUE;
      $modules_to_uninstall[] = $module;
    }
  }

  if ($needs_uninstalling) {
    $uninstalled = $module_installer->uninstall($modules_to_uninstall);

    $module_installer->install([
      'wxt_ext_layout',
      'wxt_ext_landing_page',
    ]);
  }

  if ($needs_uninstalling && !$uninstalled) {
    \Drupal::configFactory()
      ->getEditable('core.extension')
      ->clear('module.lightning_layout')
      ->clear('module.lightning_banner_block')
      ->clear('module.lightning_landing_page')
      ->clear('module.lightning_map_block')
      ->save();
    \Drupal::keyValue('system.schema')->deleteMultiple([
      'lightning_layout',
      'lightning_banner_block',
      'lightning_landing_page',
      'lightning_map_block',
    ]);
  }

  // Don't run if the site isn't using lightning_workflow.
  $module_handler = \Drupal::service('module_handler');
  if (!$module_handler->moduleExists('lightning_workflow') && !$module_handler->moduleExists('wxt_ext_workflow')) {
    return;
  }

  // Fully uninstall Lightning Workflow.
  /** @var \Drupal\Core\Extension\ModuleInstallerInterface $module_installer */
  $module_installer = \Drupal::service('module_installer');
  $modules_to_check = [
    'lightning_workflow' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_workflow') >= 0) ? TRUE : FALSE,
    'lightning_scheduler' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_scheduler') >= 0) ? TRUE : FALSE,
  ];

  $needs_uninstalling = FALSE;
  $modules_to_uninstall = [];
  $uninstalled = TRUE;

  foreach ($modules_to_check as $module => $installed) {
    if ($installed) {
      $needs_uninstalling = TRUE;
      $modules_to_uninstall[] = $module;
    }
  }

  if ($needs_uninstalling) {
    $uninstalled = $module_installer->uninstall($modules_to_uninstall);

    $module_installer->install([
      'wxt_ext_workflow',
    ]);
  }

  if ($needs_uninstalling && !$uninstalled) {
    \Drupal::configFactory()
      ->getEditable('core.extension')
      ->clear('module.lightning_workflow')
      ->clear('module.lightning_scheduler')
      ->save();
    \Drupal::keyValue('system.schema')->deleteMultiple([
      'lightning_workflow',
      'lightning_scheduler',
    ]);
  }

}

/**
 * Updates for the WxT 4.3.3 release.
 */
function wxt_core_update_8433() {
  // Don't run if the site isn't using lightning_media.
  $module_handler = \Drupal::service('module_handler');
  if (!$module_handler->moduleExists('lightning_media') && !$module_handler->moduleExists('wxt_ext_media')) {
    return;
  }

  // Retrieve the config factory.
  $config_factory = \Drupal::configFactory();

  // Map lightning_media.settings to wxt_ext_media.settings.
  $source = $config_factory->getEditable('lightning_media.settings');
  $revision_ui = $source->get('revision_ui');
  $entity_embed_display = $source->get('entity_embed.choose_display');
  $config_factory->getEditable('wxt_ext_media.settings')
    ->set('revision_ui', $revision_ui)
    ->set('entity_embed.choose_display', $entity_embed_display)
    ->save();

  // Map third_party_settings lightning_media to wxt_ext_media.
  $entity_form_display = $config_factory->getEditable('core.entity_form_display.media.image.media_browser');
  $plugins = $entity_form_display->get('content');
  foreach ($plugins as $plugin_id => $config) {
    if (isset($plugins[$plugin_id]['third_party_settings']['lightning_media'])) {
      $options = $plugins[$plugin_id]['third_party_settings']['lightning_media'];
      unset($plugins[$plugin_id]['third_party_settings']['lightning_media']);
      $plugins[$plugin_id]['third_party_settings'] = ['wxt_ext_media' => $options];
    }
    $entity_form_display->set('content', $plugins);
    $entity_form_display->save(TRUE);
  }

  // Update Entity Browser dependency to wxt_ext_media.
  $entity_browser_config = $config_factory->getEditable('entity_browser.browser.image_browser');
  $data = $entity_browser_config->getRawData();
  if (isset($data['dependencies']['module']) && in_array('lightning_media', $data['dependencies']['module'])) {
    $key = array_search('lightning_media', $data['dependencies']['module']);
    $data['dependencies']['module'][$key] = 'wxt_ext_media';
    $entity_browser_config->setData($data);
    $entity_browser_config->save();
  }

  // Remove block_content.type.media_slideshow enforcement.
  $block_content_config = $config_factory->getEditable('block_content.type.media_slideshow');
  $data = $block_content_config->getRawData();
  if (isset($data['dependencies']['enforced']['module']) && $data['dependencies']['enforced']['module'] === ['lightning_media_slideshow']) {
    unset($data['dependencies']['enforced']['module']);
    if (empty($data['dependencies']['enforced'])) {
      unset($data['dependencies']['enforced']);
    }
    $block_content_config->setData($data);
    $block_content_config->save();
  }

  // Remove field.storage.block_content.field_slideshow_items enforcement.
  $field_storage_config = $config_factory->getEditable('field.storage.block_content.field_slideshow_items');
  $data = $field_storage_config->getRawData();
  if (isset($data['dependencies']['enforced']['module']) && $data['dependencies']['enforced']['module'] === ['lightning_media_slideshow']) {
    unset($data['dependencies']['enforced']['module']);
    if (empty($data['dependencies']['enforced'])) {
      unset($data['dependencies']['enforced']);
    }
    $field_storage_config->setData($data);
    $field_storage_config->save();
  }

  // Fully uninstall Lightning Media.
  /** @var \Drupal\Core\Extension\ModuleInstallerInterface $module_installer */
  $module_installer = \Drupal::service('module_installer');
  $modules_to_check = [
    'lightning_media' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_media') >= 0) ? TRUE : FALSE,
    'lightning_media_audio' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_media_audio') >= 0) ? TRUE : FALSE,
    'lightning_media_bulk_upload' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_media_bulk_upload') >= 0) ? TRUE : FALSE,
    'lightning_media_document' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_media_document') >= 0) ? TRUE : FALSE,
    'lightning_media_image' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_media_image') >= 0) ? TRUE : FALSE,
    'lightning_media_instagram' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_media_instagram') >= 0) ? TRUE : FALSE,
    'lightning_media_slideshow' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_media_slideshow') >= 0) ? TRUE : FALSE,
    'lightning_media_twitter' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_media_twitter') >= 0) ? TRUE : FALSE,
    'lightning_media_video' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_media_video') >= 0) ? TRUE : FALSE,
  ];

  $needs_uninstalling = FALSE;
  $modules_to_uninstall = [];
  $uninstalled = TRUE;

  foreach ($modules_to_check as $module => $installed) {
    if ($installed) {
      $needs_uninstalling = TRUE;
      $modules_to_uninstall[] = $module;
    }
  }

  if ($needs_uninstalling) {
    $uninstalled = $module_installer->uninstall($modules_to_uninstall);

    // WxT typically has all of these enabled by default.
    $module_installer->install([
      'wxt_ext_media',
      'wxt_ext_media_image',
      'wxt_ext_media_slideshow',
    ]);

    // Check if any of the lightning modules were enabled and map.
    foreach ($modules_to_check as $module => $installed) {
      if ($installed) {
        switch ($module) {
          case 'lightning_media_audio':
            $module_installer->install(['wxt_ext_media_audio']);
            break;

          case 'lightning_media_bulk_upload':
            $module_installer->install(['wxt_ext_media_bulk_upload']);
            break;

          case 'lightning_media_document':
            $module_installer->install(['wxt_ext_media_document']);
            break;

          case 'lightning_media_instagram':
            $module_installer->install(['wxt_ext_media_instagram']);
            break;

          case 'lightning_media_twitter':
            $module_installer->install(['wxt_ext_media_twitter']);
            break;

          case 'lightning_media_video':
            $module_installer->install(['wxt_ext_media_video']);
            break;
        }
      }
    }
  }

  if ($needs_uninstalling && !$uninstalled) {
    \Drupal::configFactory()
      ->getEditable('core.extension')
      ->clear('module.lightning_media')
      ->clear('module.lightning_media_audio')
      ->clear('module.lightning_media_bulk_upload')
      ->clear('module.lightning_media_document')
      ->clear('module.lightning_media_image')
      ->clear('module.lightning_media_instagram')
      ->clear('module.lightning_media_slideshow')
      ->clear('module.lightning_media_twitter')
      ->clear('module.lightning_media_video')
      ->save();
    \Drupal::keyValue('system.schema')->deleteMultiple([
      'lightning_media',
      'lightning_media_audio',
      'lightning_media_bulk_upload',
      'lightning_media_document',
      'lightning_media_image',
      'lightning_media_instagram',
      'lightning_media_slideshow',
      'lightning_media_twitter',
      'lightning_media_video',
    ]);
  }

  // Add field.storage.block_content.field_slideshow_items enforcement.
  $config_factory = \Drupal::configFactory();
  $block_content_config = $config_factory->getEditable('block_content.type.media_slideshow');
  $data = $block_content_config->getRawData();
  $data['dependencies'] = [
    'enforced' => ['module' => ['wxt_ext_media_slideshow']],
  ];
  $block_content_config->setData($data);
  $block_content_config->save();

  // Add field.storage.block_content.field_slideshow_items enforcement.
  $config_factory = \Drupal::configFactory();
  $block_content_config = $config_factory->getEditable('field.storage.block_content.field_slideshow_items');
  $data = $block_content_config->getRawData();
  $data['dependencies'] = [
    'module' => $data['dependencies']['module'],
    'enforced' => ['module' => ['wxt_ext_media_slideshow']],
  ];
  $block_content_config->setData($data);
  $block_content_config->save();

  // Fully uninstall Lightning Core.
  /** @var \Drupal\Core\Extension\ModuleInstallerInterface $module_installer */
  $module_installer = \Drupal::service('module_installer');
  $modules_to_check = [
    'lightning_core' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_core') >= 0) ? TRUE : FALSE,
    'lightning_contact_form' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_contact_form') >= 0) ? TRUE : FALSE,
    'lightning_page' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_page') >= 0) ? TRUE : FALSE,
    'lightning_roles' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_roles') >= 0) ? TRUE : FALSE,
    'lightning_search' => (\Drupal::service('update.update_hook_registry')->getInstalledVersion('lightning_search') >= 0) ? TRUE : FALSE,
  ];

  $needs_uninstalling = FALSE;
  $modules_to_uninstall = [];
  $uninstalled = TRUE;

  foreach ($modules_to_check as $module => $installed) {
    if ($installed) {
      $needs_uninstalling = TRUE;
      $modules_to_uninstall[] = $module;
    }
  }

  if ($needs_uninstalling) {
    $uninstalled = $module_installer->uninstall($modules_to_uninstall);

    $module_installer->install([
      'wxt_core',
      'wxt_ext_page',
    ]);
  }

  if ($needs_uninstalling && !$uninstalled) {
    \Drupal::configFactory()
      ->getEditable('core.extension')
      ->clear('module.lightning_core')
      ->clear('module.lightning_contact_form')
      ->clear('module.lightning_page')
      ->clear('module.lightning_roles')
      ->clear('module.lightning_search')
      ->save();
    \Drupal::keyValue('system.schema')->deleteMultiple([
      'lightning_core',
      'lightning_contact_form',
      'lightning_page',
      'lightning_roles',
      'lightning_search',
    ]);
  }

  // Record all module version numbers, including our own, in config.
  $modules = array_keys(\Drupal::moduleHandler()->getModuleList());
  array_push($modules, 'wxt_core');
  wxt_core_modules_installed($modules);

  // Ensure we keep the entity displays flagged as internal for the moment.
  $storage = \Drupal::entityTypeManager()->getStorage('entity_view_mode');
  $view_modes = $storage->loadMultiple([
    'block_content.featured',
    'node.rss',
    'node.search_index',
    'media.thumbnail',
    'media.linked',
  ]);
  /** @var \Drupal\Core\Entity\EntityViewModeInterface $view_mode */
  foreach ($view_modes as $view_mode) {
    $view_mode->setThirdPartySetting('wxt_core', 'internal', TRUE);
    $storage->save($view_mode);
  }
}

/**
 * Updates for the WxT 4.4.1 release.
 */
function wxt_core_update_8441() {
  // Add the new configuration items for the new GCWeb global footer.
  $config = Config::forTheme('wxt_bootstrap')->optional();
  $entities = [
    'block' => 'block.block.wxt_bootstrap_footer_contextual',
    'block' => 'block.block.wxt_bootstrap_footer_contextual',
    'block' => 'block.block.wxt_bootstrap_footer_contextual_fr',
    'block' => 'block.block.wxt_bootstrap_footer_top',
    'block' => 'block.block.wxt_bootstrap_footer_top_fr',
    'menu' => 'system.menu.footer-contextual',
    'menu' => 'system.menu.footer-contextual-fr',
    'menu' => 'system.menu.footer-top',
    'menu' => 'system.menu.footer-top-fr',
  ];

  foreach ($entities as $entity => $machine_name) {
    if ($config->getEntity($entity, $machine_name)) {
      $config->getEntity($entity, $machine_name)->save();
    }
  }

}

/**
 * Updates for the WxT 5.0.0 release.
 */
function wxt_core_update_8500() {
  $module_installer = \Drupal::service('module_installer');
  $moduleHandler = \Drupal::service('module_handler');

  // Uninstall wxt_ext_config to prepare for removal in future release.
  if ($moduleHandler->moduleExists('wxt_ext_config')) {
    $module_installer->uninstall(['wxt_ext_config']);
  }

  // Fix block visibility config.
  $config_factory = \Drupal::service('config.factory');
  $block_configurations = $config_factory->listAll('block.block');

  foreach ($block_configurations as $config_name) {
    // Load the block configuration.
    $config = $config_factory->getEditable($config_name);

    // Check for a value and update it if needed.
    if (is_array($config->get('visibility.node_type'))) {
      if ($config->get('visibility.node_type')['id'] === 'node_type') {
        $config->set('visibility.node_type.id', 'entity_bundle:node');
        $config->save();
      }
    }
  }

  // Enable ckeditor4_codemirror for seamless transition of CKE4 text formats.
  if (!$moduleHandler->moduleExists('ckeditor4_codemirror')) {
    $module_installer->install(['ckeditor4_codemirror']);
  }
}

/**
 * Setup CountryManager lists [#3111375].
 */
function wxt_core_update_8501() {
  $config_namespace = 'wxt_core.settings.countries';
  $module_handler = \Drupal::service('module_handler');
  $module_path = $module_handler->getModule('wxt_core')->getPath();
  $path = DRUPAL_ROOT . '/' . $module_path . '/config/install/' . $config_namespace . '.yml';
  $country_data = Yaml::parse(\file_get_contents($path));

  // Get the configuration factory service.
  $config_factory = \Drupal::configFactory();

  // Save the configuration using the loaded data.
  $config = $config_factory->getEditable($config_namespace);
  $config->setData($country_data);
  $config->save();
}

/**
 * Issue #3399929: Change wxt_core countries config namespace.
 */
function wxt_core_update_8502() {
  $legacy = 'wxt_core_countries.settings';
  $updated = 'wxt_core.settings.countries';
  $config_factory = \Drupal::configFactory();
  $module_handler = \Drupal::service('module_handler');
  $module_path = $module_handler->getModule('wxt_core')->getPath();
  $path = DRUPAL_ROOT . '/' . $module_path . '/config/install/' . $updated . '.yml';
  $hasUpdated = $config_factory->get($legacy)->isNew();
  if ($hasUpdated) {
    $country_data = $config_factory->getEditable($legacy);
    $config = $config_factory->getEditable($updated);
    if (!is_array($country_data)) {
      // Update hook 8501 wasn't run correctly for some reason, or the yml was
      // deleted.
      wxt_core_update_8501();
      return;
    }
    $config->setData($country_data);
    $config->save();
    // Delete old data.
    $country_data->delete();
  }
  else {
    $country_data = Yaml::parse(\file_get_contents($path));
    $config = $config_factory->getEditable($updated);
    $config->setData($country_data);
    $config->save();
  }
}
