<?php

declare(strict_types=1);

namespace Drupal\animated_gif\Hook;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Hook\Attribute\Hook;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\animated_gif\Service\AnimatedGifInterface;
use Drupal\file\FileInterface;

/**
 * Hook form alter.
 */
class FieldWidgetFormAlter {

  use StringTranslationTrait;

  public function __construct(
    protected EntityTypeManagerInterface $entityTypeManager,
    protected AnimatedGifInterface $animatedGif,
  ) {}

  /**
   * Implements hook_field_widget_single_element_WIDGET_TYPE_form_alter().
   */
  #[Hook('field_widget_single_element_image_image_form_alter')]
  public function fieldWidgetSingleElementImageImageFormAlter(array &$element, FormStateInterface $form_state, array $context): void {
    if (!\is_array($element['#default_value']['fids']) || empty($element['#default_value']['fids'])) {
      return;
    }

    /** @var string $fid */
    $fid = \reset($element['#default_value']['fids']);
    $file = $this->entityTypeManager->getStorage('file')
      ->load($fid);

    if (!($file instanceof FileInterface)) {
      return;
    }

    if ($this->animatedGif->isFileAnAnimatedGif($file)) {
      $element[] = [
        '#theme' => 'status_messages',
        '#message_list' => [
          'warning' => [
            $this->t('GIF images are not being processed by image styles, use with caution!'),
          ],
        ],
      ];
    }
  }

}
