<?php

/**
 * @file
 * Install, update and uninstall functions for the social_embed module.
 */

use Drupal\Core\Config\FileStorage;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;

/**
 * Implements hook_install().
 *
 * Perform actions related to the installation of social_embed.
 */
function social_embed_install(bool $is_syncing) {
  // Grant the default permissions for this feature.
  user_role_grant_permissions(
    'anonymous',
    [
      'generate social embed content',
    ]
  );
  user_role_grant_permissions(
    'authenticated',
    [
      'generate social embed content',
    ]
  );
  user_role_grant_permissions(
    'sitemanager',
    [
      'administer social embed settings',
    ]
  );

  if (!$is_syncing) {
    social_embed_update_11003();
    social_embed_update_11004();
  }

  // Add the embed button to the toolbar.
  $config_factory = \Drupal::configFactory();
  $text_formats = [
    'editor.editor.full_html',
    'editor.editor.basic_html',
  ];

  // Make sure our url_embed is installed, so we can add it to the toolbar.
  \Drupal::service('module_installer')->install(['url_embed']);

  foreach ($text_formats as $text_format) {
    $configuration = $config_factory->getEditable($text_format);
    $toolbar_items = $configuration->getOriginal('settings.toolbar.items');

    // Only add the embed button when it is not on the toolbar yet.
    if (!empty($toolbar_items) && !in_array('urlembed', $toolbar_items, TRUE)) {
      $toolbar_items[] = 'urlembed';
      $configuration->set('settings.toolbar.items', $toolbar_items);
      $configuration->save();
    }
  }
}

/**
 * Implements hook_uninstall().
 *
 * Remove embed button from the toolbar.
 */
function social_embed_uninstall() :void {
  $config_factory = \Drupal::configFactory();
  $text_formats = [
    'editor.editor.full_html',
    'editor.editor.basic_html',
  ];

  foreach ($text_formats as $text_format) {
    $configuration = $config_factory->getEditable($text_format);
    $toolbar_items = $configuration->getOriginal('settings.toolbar.items');

    // Only remove the embed button when it can be found on the toolbar.
    if (!empty($toolbar_items) && $key = array_search('urlembed', $toolbar_items, TRUE)) {
      unset($toolbar_items[$key]);
      $configuration->set('settings.toolbar.items', $toolbar_items);
      $configuration->save();
    }
  }
}

/**
 * Create the social_embed icon.
 */
function social_embed_update_8001() {
  // Create the social_embed icon.
  // Removed code as the functionality behind it has been removed.
  // We don't use our own embed icon anymore.
}

/**
 * Enable 'administer url_embed' permission for sitemanagers.
 */
function social_embed_update_10301() {
  user_role_grant_permissions('sitemanager', ['administer url_embed']);
}

/**
 * Add permissions for site manager to access embed consent settings form.
 */
function social_embed_update_11001() :void {
  // Grant the default permissions for this feature.
  user_role_grant_permissions(
    'anonymous',
    [
      'generate social embed content',
    ]
  );
  user_role_grant_permissions(
    'authenticated',
    [
      'generate social embed content',
    ]
  );
  user_role_grant_permissions(
    'sitemanager',
    [
      'administer social embed settings',
    ]
  );
}

/**
 * Install field_user_embed_content_consent field to user entity.
 */
function social_embed_update_11002() :void {
  $config_directory_path = \Drupal::service('extension.list.module')->getPath('social_embed') . '/config/install';
  $config_directory = new FileStorage($config_directory_path);
  $field_storage_name = 'field.storage.user.field_user_embed_content_consent';
  $config_record = $config_directory->read($field_storage_name);
  if (is_array($config_record)
    && !empty($config_record['entity_type'])
    && !empty($config_record['field_name'])
    && (empty(FieldStorageConfig::loadByName($config_record['entity_type'], $config_record['field_name'])))
  ) {
    FieldStorageConfig::create($config_record)->save();
  }
  $field_config_name = 'field.field.user.user.field_user_embed_content_consent';
  $config_record = $config_directory->read($field_config_name);
  if (is_array($config_record)
    && !empty($config_record['entity_type'])
    && !empty($config_record['field_name'])
    && (empty(FieldConfig::loadByName($config_record['entity_type'], $config_record['bundle'], $config_record['field_name'])))
    ) {
    FieldConfig::create($config_record)->save();
  }
}

/**
 * Add new field 'field_user_embed_content_consent' to user edit form.
 *
 * This enables the user to toggle the option for embedded content settings.
 */
function social_embed_update_11003(): void {
  // Add the new field to user entity form display.
  $form_display = \Drupal::service('entity_display.repository')->getFormDisplay('user', 'user');
  $form_display = $form_display->setComponent('field_user_embed_content_consent', [
    'label' => 'above',
    'type' => 'boolean_checkbox',
  ]);
  $form_display->save();
}

/**
 * Add new field_group 'group_remote_content_settings' to user edit form.
 *
 * And add the newly installed field 'field_user_embed_content_consent'
 * as its children.
 */
function social_embed_update_11004(): void {
  // Add it to a field group now.
  $form_display = \Drupal::service('entity_display.repository')->getFormDisplay('user', 'user');
  if (!empty($form_display->getComponent('field_user_embed_content_consent'))) {
    $new_group = (object) [
      'group_name' => 'group_remote_content_settings',
      'entity_type' => 'user',
      'bundle' => 'user',
      'mode' => 'default',
      'context' => 'form',
      'children' => [
        0 => 'field_user_embed_content_consent',
      ],
      'parent_name' => '',
      'weight' => 20,
      'format_type' => 'fieldset',
      'region' => 'hidden',
      'format_settings' => [
        'show_empty_fields' => 0,
        'id' => '',
        'classes' => '',
        'description' => '',
        'required_fields' => 1,
      ],
      'label' => t('Remote content settings'),
    ];

    field_group_group_save($new_group);
  }
}

/**
 * Add urlembed icon to the toolbar as we removed it from the config override.
 */
function social_embed_update_11005(): void {
  // Add the embed button to the toolbar.
  $config_factory = \Drupal::configFactory();
  $text_formats = [
    'editor.editor.full_html',
    'editor.editor.basic_html',
  ];

  foreach ($text_formats as $text_format) {
    $configuration = $config_factory->getEditable($text_format);
    $toolbar_items = $configuration->getOriginal('settings.toolbar.items');

    // Only add the embed button when it is not on the toolbar yet.
    if (!empty($toolbar_items) && !in_array('urlembed', $toolbar_items, TRUE)) {
      $toolbar_items[] = 'urlembed';
      $configuration->set('settings.toolbar.items', $toolbar_items);
      $configuration->save();
    }
  }
}

/**
 * Change lazy-filter to use the social lazy-filter.
 */
function social_embed_update_124001(): void {
  $config_factory = \Drupal::configFactory();
  $text_formats = [
    'filter.format.full_html',
    'filter.format.basic_html',
    'filter.format.plain_text',
    'filter.format.simple_text',
    'filter.format.restricted_html',
    'filter.format.mail_html',
  ];

  foreach ($text_formats as $text_format) {
    $configuration = $config_factory->getEditable($text_format);
    $filters = $configuration->get('filters');

    // Removing old plugin when is enabled.
    if (isset($filters['lazy_filter'])) {
      unset($filters['lazy_filter']);
    }

    // Adding the lazy filter for all.
    $filters['social_embed_lazy_filter'] = [
      'id' => 'social_embed_lazy_filter',
      'provider' => 'social_embed',
      'status' => TRUE,
      'weight' => 999,
      'settings' => [],
    ];

    // Saving new filters.
    $configuration->set('filters', $filters)
      ->save();
  }
}

/**
 * Add new config `max_embeds_per_content`.
 */
function social_embed_update_124002(): void {
  // Load the existing configuration object.
  $config = \Drupal::configFactory()->getEditable('social_embed.settings');

  // Add the new configuration value if it doesn't already exist.
  if (!$config->get('max_embeds_per_content')) {
    $config->set('max_embeds_per_content', '5');
    $config->save();
  }
}
