<?php

/**
 * @file
 * Update hooks for the Entity browser module.
 */

/**
 * Updates submit text for existing Entity browsers.
 */
function entity_browser_update_8001() {
  /** @var \Drupal\Core\Config\ConfigFactoryInterface $config_factory */
  $config_factory = \Drupal::service('config.factory');

  foreach ($config_factory->listAll('entity_browser.browser') as $name) {
    $entity_browser = $config_factory->getEditable($name);
    if ($text = $entity_browser->get('submit_text')) {
      $entity_browser->clear('submit_text');
      foreach ($entity_browser->get('widgets') as $widget_uuid => $widget) {
        $entity_browser->set("widgets.$widget_uuid.settings.submit_text", $text);
        $entity_browser->save();
      }
    }
  }
}

/**
 * Migrates duplicated Views entity_browser_select fields.
 */
function entity_browser_update_8002() {
  // Map entity data tables to base tables.
  $table_map = [];
  foreach (\Drupal::entityTypeManager()->getDefinitions() as $entity_type_name => $entity_type) {
    $base_table = $entity_type->getBaseTable();
    $data_table = $entity_type->getDataTable();
    if ($base_table && $data_table) {
      $table_map[$data_table] = $base_table;
    }
  }

  $config_factory = \Drupal::configFactory();
  foreach ($config_factory->listAll('views.view.') as $view_config_name) {
    $save = FALSE;
    $view = $config_factory->getEditable($view_config_name);
    $displays = $view->get('display');
    foreach ($displays as $display_name => &$display) {
      if ($display['display_options'] && isset($display['display_options']['fields'])) {
        foreach ($display['display_options']['fields'] as $field_name => &$field) {
          if ($field['plugin_id'] === 'entity_browser_select' && isset($table_map[$field['table']])) {
            $field['table'] = $table_map[$field['table']];
            $save = TRUE;
          }
        }
      }
    }
    if ($save) {
      $view->set('display', $displays);
      $view->save(TRUE);
    }
  }
}
