<?php

/**
 * @file
 * Contains social_language.module.
 */

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Url;

/**
 * Implements hook_language_switch_links_alter().
 */
function social_language_language_switch_links_alter(array &$links, $type, Url $url) {
  $currentLangcode = \Drupal::languageManager()->getCurrentLanguage()->getId();

  foreach ($links as $langcode => &$link) {
    $link['attributes']['title'] = $link['title'];
    $link['title'] .= " (${langcode})";
    $link['attributes']['class'][] = $langcode === $currentLangcode ? 'active' : NULL;
  }
}

/**
 * Implements hook_form_alter().
 */
function social_language_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Move the fields to group_settings.
  if (isset($form['#fieldgroups']['group_settings'])) {
    // As translation form fields are added directly to forms bypassing
    // entity form display we can't have both approaches (OS and user own)
    // for field managing (@see social_core_form_node_form_alter()).
    if (isset($form['content_translation']) && Element::isVisibleElement($form['content_translation'])) {
      // Change element type for "content_translation" to be consistent
      // with general approach in OS.
      $form['#fieldgroups']['group_settings']->children[] = 'content_translation';
      $form['content_translation']['#group'] = 'group_settings';
    }

    if (isset($form['source_langcode']) && Element::isVisibleElement($form['source_langcode'])) {
      // Move "source_langcode" form element to general settings fieldset.
      $form['#fieldgroups']['group_settings']->children[] = 'source_langcode';
      $form['source_langcode']['#group'] = 'group_settings';
    }
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function social_language_form_user_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  /** @var \Drupal\Core\Config\ImmutableConfig $language_types */
  $language_negotiations = \Drupal::configFactory()->get('language.types')->get('negotiation');

  // Show the preferred language field only when the user language negotiation
  // is set to user and we have at least two languages.
  if (isset($language_negotiations['language_interface']['enabled']['language-user']) && count(\Drupal::languageManager()->getLanguages()) > 1) {
    $form['language']['#title'] = NULL;
    $form['language']['preferred_langcode']['#title'] = t('Interface language');
    $form['language']['preferred_langcode']['#description'] = t('Select the language you want to use this site in.');
    $form['language']['#attributes']['class'][] = 'form-horizontal';
  }
  else {
    $form['language']['#access'] = FALSE;
  }
}

/**
 * Implements hook_default_route_group_tabs_alter().
 */
function social_language_social_group_default_route_tabs_alter(&$tabs) {
  // Unset some tabs created by group.
  unset($tabs['content_translation.local_tasks:entity.group.content_translation_overview']);
}

/**
 * Implements hook_entity_operation_alter().
 */
function social_language_entity_operation_alter(array &$operations, EntityInterface $entity): array {
  // "Content Translations" module allows to add translations
  // to the entity that user can't edit...This cause displaying
  // the redundant operation "translate" in entity list pages.
  /* @see content_translation_translate_access() */
  if (!empty($operations['translate'])) {
    // All checks are already done in social_language_entity_operation()
    // and we need only add the last one.
    if (!$entity->access('update')) {
      // Remove the operation if user can't edit entity.
      unset($operations['translate']);
    }
  }
  return $operations;
}

/**
 * Implements hook_field_group_form_process_alter().
 */
function social_language_field_group_form_process_alter(array &$element, &$group, &$complete_form) {
  // Prevent \Drupal\content_translation\ContentTranslationHandler::addTranslatabilityClue()
  // from adding an incorrect suffix to the field group title.
  $element['#multilingual'] = TRUE;
}

/**
 * Implements hook_modules_installed().
 */
function social_language_modules_installed($modules) {
  // When "Content Translation" module enabled, it provides few additional
  // fields for translated entities. After fields are added, Drupal requires
  // these fields definitions to be updated. Technically this is proceeded
  // after submit this form "/admin/config/regional/content-language".
  // But in OS this approach doesn't work as SM doesn't have access to the page.
  // So, here we track any module installation and check if there are updates
  // for translations fields and run updates.
  $change_list = \Drupal::entityDefinitionUpdateManager()->getChangeList();

  if ($change_list) {
    foreach ($change_list as $entity_type_id => $changes) {
      // We check only "content_translation_source"
      // as this field should exist everytime.
      if (!empty($changes['field_storage_definitions']['content_translation_source'])) {
        if (function_exists('_content_translation_install_field_storage_definitions')) {
          _content_translation_install_field_storage_definitions($entity_type_id);
        }
      }
    }
  }
}

/**
 * Implements hook_preprocess_HOOK().
 */
function social_language_preprocess_locale_translation_update_info(array &$variables): void {
  foreach ($variables['updates'] as &$update) {
    if (!is_int($update['timestamp'])) {
      $update['timestamp'] = 0;
    }
  }
}
