<?php

/**
 * @file
 * File containing d_p_reference module.
 */

use Drupal\Core\Template\Attribute;

/**
 * Implements hook_theme().
 */
function d_p_reference_content_theme($existing, $type, $theme, $path) {
  return [
    'paragraph__d_p_reference_content' => [
      'base hook' => 'paragraph',
    ],
    'field__paragraph__field_d_p_reference_content' => [
      'base hook' => 'field',
    ],
    'field__paragraph__field_d_main_title__d_p_reference_content' => [
      'base hook' => 'field',
    ],
    'field__paragraph__field_d_cta_link__d_p_reference_content' => [
      'base hook' => 'field',
    ],
    'field__paragraph__field_d_media_icon__d_p_reference_content' => [
      'base hook' => 'field',
    ],
    'field__paragraph__field_d_long_text__d_p_reference_content' => [
      'base hook' => 'field',
    ],
  ];
}

/**
 * Implements hook_preprocess_HOOK().
 */
function d_p_reference_content_preprocess_paragraph__d_p_reference_content(array &$variables) {
  /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
  $paragraph = $variables['paragraph'];

  $variables['d_p_reference_content_wrapper_attributes'] = new Attribute();

  // Current manually values.
  $reference_content = $paragraph->get('field_d_p_reference_content');
  $values = $reference_content->getValue();

  // Get latest blog node nids.
  // Selected nodes are excluded from results.
  /** @var \Drupal\d_p_reference_content\Helpers\ContentHelper $content_helper */
  $content_helper = \Drupal::service('d_p_reference_content.content_helper');
  $auto_values = $content_helper->getSortedContentByType('blog_post', 'created', 'DESC', $values);
  $merged_values = array_merge($values, $auto_values);

  // Delete unpublished content.
  $merged_values = $content_helper->getPublishedContent($merged_values);

  // Get max number of values.
  /** @var \Drupal\field\Entity\FieldConfig $def */
  $def = $reference_content->getDataDefinition();
  $cardinality = $def->getFieldStorageDefinition()->getCardinality();
  $min = min(count($merged_values), $cardinality);

  // Build an array with new values.
  $new_values = [];
  for ($i = 0; $i < $min; $i++) {
    $new_values[] = $merged_values[$i];
  }

  // Replace content.
  $content_helper->replaceContent($variables, 'node', 'teaser_small', 'field_d_p_reference_content', $new_values);

  $variables['#cache']['tags'][] = 'node_list';
}
