<?php

namespace Drupal\pagedesigner_image\Plugin\pagedesigner\Handler;

use Drupal\pagedesigner\Entity\Element;
use Drupal\pagedesigner_media\Plugin\MediaFieldHandlerBase;

/**
 * Process entities of type "image".
 *
 * @PagedesignerHandler(
 *   id = "image",
 *   name = @Translation("Image handler"),
 *   types = {
 *      "image",
 *      "img",
 *   },
 * )
 */
class Image extends MediaFieldHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function collectAttachments(array &$attachments) {
    $attachments['library'][] = 'pagedesigner_image/pagedesigner';
    static::addMediaTypeInfo($attachments, 'image');
  }

  /**
   * {@inheritdoc}
   */
  public function serialize(Element $entity, array &$result = []) {
    $data = [
      'src' => '',
      'id' => $entity->field_media->target_id,
    ];
    $medium = static::getMediaTranslation($entity->field_media->entity);
    if ($medium != NULL && $medium->field_media_image->entity != NULL) {
      $data['src'] = $medium->field_media_image->entity->createFileUrl();
    }
    $result = $data + $result;
  }

  /**
   * {@inheritdoc}
   */
  public function get(Element $entity, string &$result = '') {
    $medium = static::getMediaTranslation($entity->field_media->entity);
    if ($medium != NULL && $medium->field_media_image->entity != NULL) {
      $file = $medium->field_media_image->entity;

      // Apply default image style, if available.
      /** @var \Drupal\image\Entity\ImageStyle $style */
      $style = $this->entityTypeManager
        ->getStorage('image_style')
        ->load('pagedesigner_default');
      if ($style != NULL) {
        $result = $style->buildUrl($file->getFileUri());
      }
      else {
        $result = $file->createFileUrl();
      }

    }
  }

  /**
   * {@inheritdoc}
   */
  public function generate($definition, array $data, ?Element &$entity = NULL) {
    parent::generate(['type' => 'image', 'name' => 'image'], $data, $entity);
  }

}
