<?php

/**
 * @file
 * Contains paragraphs.module
 */

use Drupal\Core\Url;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\field\FieldStorageConfigInterface;
use Drupal\field\Plugin\migrate\source\d7\Field;
use Drupal\field\Plugin\migrate\source\d7\FieldInstance;
use Drupal\field\Plugin\migrate\source\d7\ViewMode;
use Drupal\migrate_drupal\Plugin\migrate\FieldMigration;
use Drupal\paragraphs\Entity\ParagraphsType;
use Drupal\paragraphs\Plugin\migrate\field\FieldCollection;
use Drupal\Core\Render\Element;

/**
 * Implements hook_help().
 */
function paragraphs_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the paragraphs module.
    case 'help.page.paragraphs':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The Paragraphs module provides a field type that can contain several other fields and thereby allows users to break content up on a page. Administrators can predefine <em>Paragraphs types</em> (for example a simple text block, a video, or a complex and configurable slideshow). Users can then place them on a page in any order instead of using a text editor to add and configure such elements. For more information, see the <a href=":online">online documentation for the Paragraphs module</a>.', [':online' => 'https://www.drupal.org/node/2444881']) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dt>' . t('Creating Paragraphs types') . '</dt>';
      $output .= '<dd>' . t('<em>Paragraphs types</em> can be created by clicking <em>Add Paragraphs type</em> on the <a href=":paragraphs">Paragraphs types page</a>. By default a new Paragraphs type does not contain any fields.', [':paragraphs' => Url::fromRoute('entity.paragraphs_type.collection')->toString()]) . '</dd>';
      $output .= '<dt>' . t('Configuring Paragraphs types') . '</dt>';
      $output .= '<dd>' . t('Administrators can add fields to a <em>Paragraphs type</em> on the <a href=":paragraphs">Paragraphs types page</a> if the <a href=":field_ui">Field UI</a> module is enabled. The form display and the display of the Paragraphs type can also be managed on this page. For more information on fields and entities, see the <a href=":field">Field module help page</a>.', [':paragraphs' => Url::fromRoute('entity.paragraphs_type.collection')->toString(), ':field' => Url::fromRoute('help.page', ['name' => 'field'])->toString(), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? Url::fromRoute('help.page', ['name' => 'field_ui'])->toString() : '#']) . '</dd>';
      $output .= '<dt>' . t('Creating content with Paragraphs') . '</dt>';
      $output .= '<dd>' . t('Administrators can add a <em>Paragraph</em> field to content types or other entities, and configure which <em>Paragraphs types</em> to include. When users create content, they can then add one or more paragraphs by choosing the appropriate type from the dropdown list. Users can also dragdrop these paragraphs. This allows users to add structure to a page or other content (for example by adding an image, a user reference, or a differently formatted block of text) more easily then including it all in one text field or by using fields in a pre-defined order.') . '</dd>';
      return $output;
    break;
  }
}

function paragraphs_type_get_types() {
  return ParagraphsType::loadMultiple();
}

function paragraphs_type_get_names() {
  return array_map(function ($bundle_info) {
    return $bundle_info['label'];
  }, \Drupal::service('entity_type.bundle.info')->getBundleInfo('paragraphs_type'));
}

function paragraphs_type_load($name) {
  return ParagraphsType::load($name);
}

/**
 * Implements hook_theme().
 */
function paragraphs_theme() {
  return array(
    'paragraph' => array(
      'render element' => 'elements',
    ),
    'paragraphs_dropbutton_wrapper' => array(
      'variables' => array('children' => NULL),
    ),
    'paragraphs_info_icon' => [
      'variables' => [
        'message' => NULL,
        'icon' => NULL,
      ],
    ],
    'paragraphs_add_dialog' => [
      'render element' => 'element',
      'template' => 'paragraphs-add-dialog',
    ],
    'paragraphs_actions' => [
      'render element' => 'element',
      'template' => 'paragraphs-actions',
    ],
  );
}

/**
 * Implements hook_theme_suggestions_HOOK().
 */
function paragraphs_theme_suggestions_paragraph(array $variables) {
  $suggestions = array();
  $paragraph = $variables['elements']['#paragraph'];
  $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');

  $suggestions[] = 'paragraph__' . $sanitized_view_mode;
  $suggestions[] = 'paragraph__' . $paragraph->bundle();
  $suggestions[] = 'paragraph__' . $paragraph->bundle() . '__' . $sanitized_view_mode;

  return $suggestions;
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function paragraphs_form_entity_form_display_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $field_definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions($form['#entity_type'], $form['#bundle']);
  // Loop over ERR field's display options with paragraph target type.
  foreach (array_keys($field_definitions) as $field_name) {
    if ($field_definitions[$field_name]->getType() == 'entity_reference_revisions') {
      if ($field_definitions[$field_name]->getSettings()['target_type'] == 'paragraph') {
        foreach (['options_buttons', 'options_select', 'entity_reference_revisions_autocomplete'] as $option) {
          unset($form['fields'][$field_name]['plugin']['type']['#options'][$option]);
        }
      }
    }
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function paragraphs_form_field_storage_config_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_state->getFormObject()->getEntity()->getType() == 'entity_reference') {
    // Entity Reference fields are no longer supported to reference Paragraphs.
    unset($form['settings']['target_type']['#options'][(string) t('Content')]['paragraph']);
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Indicate unsupported multilingual paragraphs field configuration.
 */
function paragraphs_form_field_config_edit_form_alter(&$form,  \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $field = $form_state->getFormObject()->getEntity();

  if (!\Drupal::hasService('content_translation.manager')) {
    return;
  }

  $bundle_is_translatable = \Drupal::service('content_translation.manager')
    ->isEnabled($field->getTargetEntityTypeId(), $field->getTargetBundle());

  if (!$bundle_is_translatable
    || $field->getType() != 'entity_reference_revisions'
    || $field->getSetting('target_type') != 'paragraph') {
    return;
  }

  // This is a translatable ERR field pointing to a paragraph.
  $message_display = 'warning';
  $message_text = t('Paragraphs fields do not support translation. See the <a href=":documentation">online documentation</a>.', [
    ':documentation' => Url::fromUri('https://www.drupal.org/node/2735121')
      ->toString()
  ]);

  if ($form['translatable']['#default_value'] == TRUE) {
    $message_display = 'error';
  }

  $form['paragraphs_message'] = array(
    '#type' => 'container',
    '#markup' => $message_text,
    '#attributes' => array(
      'class' => array('messages messages--' . $message_display),
    ),
    '#weight' => 0,
  );
}

/**
 * Implements hook_module_implements_alter().
 *
 * Our paragraphs_form_field_config_edit_form_alter() needs to be run after
 * that of the content_translation module in order to see the current state
 * of the translation field.
 *
 * The hook here can't be more specific, as the $hook that's passed in to this
 * function is form_alter, and not form_FORM_ID_alter.
 */
function paragraphs_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter' && isset($implementations['paragraphs'])) {
    $group = $implementations['paragraphs'];
    unset($implementations['paragraphs']);
    $implementations['paragraphs'] = $group;
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Indicate unsupported multilingual paragraphs field configuration.
 *
 * Add a warning that paragraph fields can not be translated.
 * Switch to error if a paragraph field is marked as translatable.
 */
function paragraphs_form_language_content_settings_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // Without it Paragraphs message are meaningless.
  if (!\Drupal::hasService('content_translation.manager')) {
    return;
  }

  $content_translation_manager = \Drupal::service('content_translation.manager');
  $message_display = 'warning';
  $message_text = t('(* unsupported) Paragraphs fields do not support translation. See the <a href=":documentation">online documentation</a>.', [
    ':documentation' => Url::fromUri('https://www.drupal.org/node/2735121')
      ->toString()]);
  $map = \Drupal::service('entity_field.manager')->getFieldMapByFieldType('entity_reference_revisions');
  foreach ($map as $entity_type_id => $info) {
    if (!$content_translation_manager->isEnabled($entity_type_id)) {
      continue;
    }
    $field_storage_definitions = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions($entity_type_id);

    /** @var \Drupal\Core\Field\FieldStorageDefinitionInterface  $storage_definition */
    foreach ($field_storage_definitions as $name => $storage_definition) {
      if ($storage_definition->getSetting('target_type') && $storage_definition->getSetting('target_type') == 'paragraph') {

        // For configurable fields, check all bundles on which the field exists,
        // for base fields that are translable, check all bundles,
        // untranslatable base fields do not show up at all.
        $bundles = [];
        if ($storage_definition instanceof FieldStorageConfigInterface) {
          $bundles = $storage_definition->getBundles();
        }
        elseif ($storage_definition->isTranslatable()) {
          $bundles = Element::children($form['settings'][$entity_type_id]);
        }
        foreach($bundles as $bundle) {
          if (!$content_translation_manager->isEnabled($entity_type_id, $bundle)) {
            continue;
          }

          // Update the label and if the paragraph field is translatable,
          // display an error message instead of just a warning.
          if (isset($form['settings'][$entity_type_id][$bundle]['fields'][$name]['#label'])) {
            $form['settings'][$entity_type_id][$bundle]['fields'][$name]['#label'] = t('@field_label (* unsupported)', ['@field_label' => $form['settings'][$entity_type_id][$bundle]['fields'][$name]['#label']]);
          }
          if (!empty($form['settings'][$entity_type_id][$bundle]['fields'][$name]['#default_value'])) {
            $message_display = 'error';
          }
        }
      }
    }
  }

  // Update the description on the hide untranslatable fields checkbox.
  if (isset($form['settings']['paragraph'])) {
    $paragraph_untranslatable_hide_description = t('Paragraph types that are used in moderated content requires non-translatable fields to be edited in the original language form and this must be checked.');
    foreach (Element::children($form['settings']['paragraph']) as $bundle) {
      if (!empty($form['settings']['paragraph'][$bundle]['settings']['content_translation']['untranslatable_fields_hide'])) {
        $form['settings']['paragraph'][$bundle]['settings']['content_translation']['untranslatable_fields_hide']['#description'] = $paragraph_untranslatable_hide_description;
      }
    }
  }

  $form['settings']['paragraphs_message'] = array(
    '#type' => 'container',
    '#markup' => $message_text,
    '#attributes' => array(
      'class' => array('messages messages--' . $message_display),
    ),
    '#weight' => 0,
  );
}

/**
 * Prepares variables for paragraph templates.
 *
 * Default template: paragraph.html.twig.
 *
 * Most themes use their own copy of paragraph.html.twig. The default is located
 * inside "templates/paragraph.html.twig". Look in there for the
 * full list of variables.
 *
 * @param array $variables
 *   An associative array containing:
 *   - elements: An array of elements to display in view mode.
 *   - paragraph: The paragraph object.
 *   - view_mode: View mode; e.g., 'full', 'teaser'...
 */
function template_preprocess_paragraph(&$variables) {
  $variables['view_mode'] = $variables['elements']['#view_mode'];
  $variables['paragraph'] = $variables['elements']['#paragraph'];

  // Helpful $content variable for templates.
  $variables += array('content' => array());
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }

  $paragraph_type = $variables['elements']['#paragraph']->getParagraphType();
  foreach ($paragraph_type->getEnabledBehaviorPlugins() as $plugin_id => $plugin_value) {
    $plugin_value->preprocess($variables);
  }

}

/**
 * Prepares variables for modal form add widget template.
 *
 * Default template: paragraphs-add-dialog.html.twig
 *
 * @param array $variables
 *   An associative array containing:
 *   - buttons: An array of buttons to display in the modal form.
 */
function template_preprocess_paragraphs_add_dialog(&$variables) {
  // Define variables for the template.
  $variables += ['buttons' => []];
  foreach (Element::children($variables['element']) as $key) {
    if ($key == 'add_modal_form_area') {
      // $add variable for the add button.
      $variables['add'] = $variables['element'][$key];
    }
    else {
      // Buttons for the paragraph types in the modal form.
      $variables['buttons'][$key] = $variables['element'][$key];
    }
  }
}

/**
 * Prepares variables for paragraphs_actions component.
 *
 * Default template: paragraphs-actions.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - actions: An array of default action buttons.
 *   - dropdown_actions: An array of buttons for dropdown.
 */
function template_preprocess_paragraphs_actions(&$variables) {
  // Define variables for the template.
  $variables += ['actions' => [], 'dropdown_actions' => []];

  $element = $variables['element'];

  if (!empty($element['actions'])) {
    $variables['actions'] = $element['actions'];
  }

  if (!empty($element['dropdown_actions'])) {
    $variables['dropdown_actions'] = $element['dropdown_actions'];
  }
}

/**
 * Implements hook_preprocess_HOOK() for field_multiple_value_form().
 */
function paragraphs_preprocess_field_multiple_value_form(&$variables) {
  if (!empty($variables['table']['#header']) && isset($variables['table']['#rows'])) {
    // Find paragraph_actions and move to header.
    // @see template_preprocess_field_multiple_value_form()
    if (!empty($variables['table']['#rows'][0]['data'][1]['data']['#paragraphs_header'])) {
      $variables['table']['#header'][0]['data'] = [
        'title' => $variables['table']['#header'][0]['data'],
        'button' => $variables['table']['#rows'][0]['data'][1]['data'],
      ];
      unset($variables['table']['#rows'][0]);
    }

    // Add the paragraph type as a class to every row.
    if (isset($variables['element'][0]['#paragraph_type'])) {
      foreach ($variables['table']['#rows'] as $key => $row) {
        if (isset($row['data'][1]['data']['#paragraph_type'])) {
          $variables['table']['#rows'][$key]['class'][] = 'paragraph-type--' . str_replace('_', '-', $row['data'][1]['data']['#paragraph_type']);
        }
      }
    }
  }

  // Remove the drag handler if we are translating, if the field's cardinality
  // is 1 or if there are no paragraphs added. Passing through this will not
  // only remove the drag handler but also the order column that is empty when
  // no paragraphs are added and when the field is single value.
  if ((isset($variables['element']['#allow_reference_changes']) && !$variables['element']['#allow_reference_changes']) || (isset($variables['element']['#cardinality']) && $variables['element']['#cardinality'] == 1) || (isset($variables['table']['#rows']) && count($variables['table']['#rows']) == 0)) {
    if (isset($variables['table']['#tabledrag'])) {
      // Remove the tabledrag.
      unset($variables['table']['#tabledrag']);
      unset($variables['table']['#header'][1]);
      foreach ($variables['table']['#rows'] as $key => $value) {
        $variables['table']['#rows'][$key]['data'][0]['class'][] = 'paragraph-bullet';
        // Restore the removed weight and give access FALSE.
        $variables['table']['#rows'][$key]['data'][1]['data']['_weight'] = $value['data'][2]['data'];
        unset($variables['table']['#rows'][$key]['data'][2]);
        $variables['table']['#rows'][$key]['data'][1]['data']['_weight']['#access'] = FALSE;
      }
    }
  }
}

/**
 * Implements hook_libraries_info().
 */
function paragraphs_libraries_info() {
  $libraries = [
    'Sortable' => [
      'name' => 'Sortable',
      'vendor url' => 'https://github.com/RubaXa/Sortable',
      'download url' => 'https://github.com/RubaXa/Sortable/releases',
      'files' => [
        'js' => [
          'Sortable.min.js' => [],
        ],
      ],
      'version arguments' => [
        // The version is at the end of the file, which is currently about 15k
        // characters long.
        'file' => 'Sortable.min.js',
        'pattern' => '/\.version="(.*?)"/',
        'lines' => 5,
        'cols' => 20000
      ]
    ],
  ];
  return $libraries;
}

/**
 * Implements hook_library_info_alter().
 */
function paragraphs_library_info_alter(&$libraries, $extension) {
  if ($extension != 'paragraphs') {
    return;
  }

  if (\Drupal::moduleHandler()->moduleExists('libraries')) {
    $info = libraries_detect('Sortable');
  }
  else {
    // If the library module is not installed, hardcode the path and fetch
    // the required information ourself.
    $library_path = 'libraries/Sortable';
    $file = 'Sortable.min.js';
    $path = DRUPAL_ROOT . '/' . $library_path . '/' . $file;
    if (file_exists($path)) {
      if (preg_match('/\.version="(.*?)"/', file_get_contents($path), $version)) {
        $info = [
          'installed' => TRUE,
          'version' => $version[1],
          'library path' => $library_path,
          'files' => [
            'js' => [
              $file => [],
            ],
          ],
        ];
      }
    }
  }

  if (!empty($info['installed'])) {
    $libraries['sortable'] += [
      'version' => $info['version'],
    ];
    // Self hosted player, use files from library definition.
    if (!empty($info['files']['js'])) {
      foreach ($info['files']['js'] as $filename => $options) {
        $libraries['sortable']['js']["/{$info['library path']}/{$filename}"] = $options;
      }
    }
  }
  else {
    // Unset the libraries if we failed to detect them.
    unset($libraries['sortable']);
    unset($libraries['paragraphs-dragdrop']);
  }

  return $libraries;
}

/**
 * Implements hook_migration_plugins_alter().
 *
 * @todo refactor/rethink this when
 * https://www.drupal.org/project/drupal/issues/2904765 is resolved
 */
function paragraphs_migration_plugins_alter(array &$migrations) {
  foreach ($migrations as $key => &$migration) {
    /** @var \Drupal\migrate\Plugin\MigrationPluginManager $migration_plugin_manager */
    $migration_plugin_manager = \Drupal::service('plugin.manager.migration');
    $migration_stub = $migration_plugin_manager->createStubMigration($migration);
    /** @var \Drupal\migrate\Plugin\MigrateSourcePluginManager $source_plugin_manager */
    $source_plugin_manager = \Drupal::service('plugin.manager.migrate.source');
    $source = NULL;
    $configuration = $migration['source'];
    $source = $source_plugin_manager->createInstance($migration['source']['plugin'], $configuration, $migration_stub);
    if ($source) {
      if (is_a($migration['class'], FieldMigration::class, TRUE)) {

        // Field storage.
        if (is_a($source, Field::class)) {
          _paragraphs_migration_entity_type_adjust($migration);
        }

        // Field instance.
        if (is_a($source, FieldInstance::class)) {
          _paragraphs_migration_entity_type_adjust($migration);
          _paragraphs_migration_bundle_adjust($migration);
          $migration['migration_dependencies']['optional']['d7_field_collection_type'] = 'd7_field_collection_type';
          $migration['migration_dependencies']['optional']['d7_paragraphs_type'] = 'd7_paragraphs_type';
        }
      }

      // View Modes.
      if (is_a($source, ViewMode::class)) {
        _paragraphs_migration_entity_type_adjust($migration, 'targetEntityType');
      }
    }
  }
}

/**
 * Implements hook_entity_type_alter().
 */
function paragraphs_entity_type_alter(array &$entity_types) {
  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
  // Remove the handler class for moderation as it is managed by the host.
  $entity_types['paragraph']->setHandlerClass('moderation', '');
}

/**
 * Remove 'field_' prefix from field collection bundles.
 *
 * @param array $migration
 *   The migration configuration to process.
 */
function _paragraphs_migration_bundle_adjust(array &$migration) {

  if (!isset($migration['process']['bundle'])) {
    $migration['process']['bundle'] = [];
  }

  $bundle_process = $migration['process']['bundle'];

  // Try to play nice with other modules altering this, and don't replace
  // it outright unless it's unchanged.
  if (array_key_exists('plugin', $bundle_process)) {
    $bundle_process = [$bundle_process];
  }
  $bundle_process['paragraphs'] = [
    'plugin' => 'paragraphs_process_on_value',
    'source_value' => 'entity_type',
    'expected_value' => 'field_collection_item',
    'process' => [
      'plugin' => 'substr',
      'start' => FieldCollection::FIELD_COLLECTION_PREFIX_LENGTH,
    ],
  ];
  $migration['process']['bundle'] = $bundle_process;
}

/**
 * Map field_collection_item and 'paragraphs_item' fields to 'paragraph'.
 *
 * @param array $migration
 *   Thei migration to process.
 * @param string $destination
 *   The process destination.
 */
function _paragraphs_migration_entity_type_adjust(array &$migration, $destination = 'entity_type') {
  $entity_type_process = $migration['process'][$destination];

  // Try to play with other modules altering this, and don't replace it
  // outright unless it's unchanged.
  if (!is_array($entity_type_process)) {
    $entity_type_process = [
      [
        'plugin' => 'get',
        'source' => 'entity_type',
      ],
    ];
  }
  $entity_type_process['paragraphs'] = [
    'plugin' => 'static_map',
    'map' => [
      'field_collection_item' => 'paragraph',
      'paragraphs_item' => 'paragraph',
    ],
    'bypass' => TRUE,
  ];
  $migration['process'][$destination] = $entity_type_process;
}
