<?php

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

use Drupal\Core\Template\Attribute;
use Drupal\d_p\ParagraphSettingTypesInterface;
use Drupal\d_p\Plugin\Field\FieldType\ConfigurationStorage;

/**
 * Implements hook_theme().
 */
function d_p_tiles_theme($existing, $type, $theme, $path) {
  return [
    'paragraph__d_p_tiles' => [
      'base hook' => 'paragraph',
    ],
    'field__paragraph__field_d_media_image__d_p_tiles' => [
      'base hook' => 'field',
    ],
    'media__d_image__tiles_gallery_fullscreen_featured' => [
      'base hook' => 'media',
    ],
    'media__d_image__d_tiles_gallery_fullscreen' => [
      'base hook' => 'media',
    ],
  ];
}

/**
 * Implements hook_preprocess_HOOK().
 */
function d_p_tiles_preprocess_paragraph__d_p_tiles(array &$variables) {
  $variables['#attached']['library'][] = 'd_p_tiles/masonry';
  $variables['#attached']['library'][] = 'd_p_tiles/d_p_tiles';
}

/**
 * Implements hook_preprocess_field().
 */
function d_p_tiles_preprocess_field(&$variables) {
  if ($variables['element']['#entity_type'] == 'paragraph') {
    /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
    $paragraph = $variables['element']['#object'];

    if ($variables['element']['#bundle'] == 'd_p_tiles') {
      switch ($variables['field_name']) {

        case 'field_d_main_title':
        case 'field_d_long_text':
          // Add container class to title and description.
          $variables['attributes']['class'][] = 'container';
          break;

        case 'field_d_media_image':
          $variables['wrapper_attributes'] = new Attribute();

          /** @var \Drupal\d_p\Plugin\Field\ConfigurationStorageFieldItemListInterface $setting_field */
          $setting_field = ConfigurationStorage::getSettingsFieldFromEntity($paragraph);
          $featured_images = $setting_field->getSettingValue(ParagraphSettingTypesInterface::PARAGRAPH_FEATURED_IMAGES);
          $featured_images = empty($featured_images) ? [] : explode(',', $featured_images);

          $featured_images = array_map('intval', $featured_images);
          foreach ($featured_images as $image_number) {
            if ($image_number > 0 && !empty($variables['items'][$image_number - 1])) {
              $variables['items'][$image_number - 1]['content']['#view_mode'] = 'tiles_gallery_fullscreen_featured';
            }
          }
          break;
      }
    }
  }
}

/**
 * Implements hook_d_p_centered_ckeditor_widget_paragraphs().
 */
function d_p_tiles_d_p_centered_ckeditor_widget_paragraphs(array &$paragraph_types) {
  $paragraph_types[] = 'd_p_tiles';
}
