<?php

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

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

/**
 * Implements hook_preprocess_HOOK().
 */
function d_p_side_tiles_preprocess_paragraph__d_p_side_tiles(array &$variables) {
  $paragraph = $variables['paragraph'];
  try {
    /** @var \Drupal\d_p\Plugin\Field\ConfigurationStorageFieldItemListInterface $setting_field */
    $setting_field = ConfigurationStorage::getSettingsFieldFromEntity($paragraph);

    $variables['tiles_side'] = $setting_field
      ->getSettingValue(ParagraphSettingTypesInterface::PARAGRAPH_SETTING_SIDE_TILES_LAYOUT);
  }
  catch (MissingConfigurationStorageFieldException $exception) {
    \Drupal::logger('d_p')->error($exception->getMessage());
  }

  $variables['#attached']['library'][] = 'd_p_tiles/masonry';
  $variables['#attached']['library'][] = 'd_p_tiles/d_p_tiles';

  $variables['tiles_wrapper_attributes'] = new Attribute();
  $variables['images_side_attributes'] = new Attribute();
  $variables['content_side_attributes'] = new Attribute();
  $variables['content_fields_attributes'] = new Attribute();
}

/**
 * Implements hook_theme().
 */
function d_p_side_tiles_theme($existing, $type, $theme, $path) {
  return [
    'paragraph__d_p_side_tiles' => [
      'base hook' => 'paragraph',
    ],
    'field__paragraph__field_d_media_image__d_p_side_tiles' => [
      'base hook' => 'field',
    ],
  ];
}

/**
 * Implements hook_preprocess_colorbox_formatter().
 */
function d_p_side_tiles_preprocess_colorbox_formatter(&$variables) {
  // Add standard size to each field.
  $variables['attributes']['class'][] = 'd-tiles-item';

  // Detect custom sizes in ALTs.
  $fd = $variables['item']->getFieldDefinition();

  /** @var \Drupal\d_p\Service\ParentParagraphService $parentEntityService */
  $parentEntityService = Drupal::service('d_p.entity_parent_paragraph');
  $paragraphFieldId = $parentEntityService->getParentParagraphFieldId($variables['entity']);

  if ($fd->id() == 'paragraph.d_p_side_tiles.field_d_media_image'
    || ($paragraphFieldId && $paragraphFieldId == 'paragraph.d_p_tiles.field_d_media_image')) {
    $variables['attributes']['data-cbox-title'] = $variables['attributes']['title'];
    $variables['attributes']['title'] = '';
  }
}
