<?php

/**
 * @file
 * Module file for d_media.
 */

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Template\Attribute;
use Drupal\image\Entity\ImageStyle;

/**
 * Implements hook_theme().
 */
function d_media_theme() {
  return [
    'd_media_video_embed' => [
      'variables' => [
        'attributes' => NULL,
        'spacer_attributes' => NULL,
      ],
    ],
    'd_media_document_embed' => [
      'variables' => [
        'link' => NULL,
        'name' => NULL,
      ],
    ],
    'd_media_canvas_image' => [
      'variables' => [
        'canvas_attributes' => NULL,
        'image' => NULL,
      ],
    ],
  ];
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function d_media_form_editor_image_dialog_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Allow upload svg file in ckeditor, if config wysiwyg_upload_svg_disable
  // is null or false.
  $form['fid']['#upload_validators']['file_validate_extensions'] = ['gif png jpg jpeg svg'];
}

/**
 * Prepares variables for canvas image templates.
 *
 * Default template: d-media-canvas-image.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - image: image render element (output of image_style theme)
 *
 * @throws \Exception
 */
function template_preprocess_d_media_canvas_image(array &$variables) {
  $style = ImageStyle::load($variables['image']['#style_name']);
  $scaling = $style->getEffects()->getIterator()->current();
  $configuration = $scaling->getConfiguration()['data'] ?? [];

  if (!empty($configuration['width']) && !empty($configuration['height'])) {
    $variables['canvas_attributes'] = new Attribute([
      'width' => $configuration['width'],
      'height' => $configuration['height'],
    ]);

    $variables['#attached']['library'][] = 'd_media/canvas-image';
  }
}
