<?php

namespace Drupal\pagedesigner_gallery\Plugin\pagedesigner\Handler;

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

/**
 * Process entities of type "gallery_gallery".
 *
 * @PagedesignerHandler(
 *   id = "gallery_component",
 *   name = @Translation("Gallery component handler"),
 *   types = {
 *      "gallery_gallery"
 *   },
 * )
 */
class GalleryGallery extends FieldHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function serialize(Element $entity, array &$result = []) {
    $data = [];
    if ($entity->children) {
      foreach ($entity->children as $item) {
        if ($item->entity != NULL) {
          $medium = MediaFieldHandlerBase::getMediaTranslation($item->entity->field_media->entity);
          if ($medium != NULL && $medium->field_media_image->entity != NULL) {
            $file = $medium->field_media_image->entity;
            $url = $previewUrl = $file->createFileUrl();
            /** @var \Drupal\image\Entity\ImageStyle $style */
            $style = $this->entityTypeManager
              ->getStorage('image_style')
              ->load('pagedesigner_default');
            if ($style != NULL) {
              $url = $previewUrl = $style->buildUrl($file->getFileUri());
            }
            /** @var \Drupal\image\Entity\ImageStyle $style */
            $style = $this->entityTypeManager
              ->getStorage('image_style')
              ->load('thumbnail');
            if ($style != NULL) {
              $previewUrl = $style->buildUrl($file->getFileUri());
            }

            $data[] = [
              'alt' => $item->entity->field_content->value,
              'id' => $item->entity->field_media->target_id,
              'src' => $url,
              'preview' => $previewUrl,
            ];
          }
        }
      }
    }
    $result = $data + $result;
  }

  /**
   * {@inheritdoc}
   */
  public function get(Element $entity, string &$result = '') {
    $data = $this->elementHandler->serialize($entity);
    $stringData = [];
    foreach ($data as $item) {
      $stringData[] = $item['alt'];
    }
    return implode(' ', $stringData);
  }

  /**
   * {@inheritdoc}
   */
  public function patch(Element $entity, array $data) {
    if (isset($data['items'])) {
      foreach ($entity->children as $item) {
        $item->entity->delete();
      }
      $entity->children->setValue([]);
      foreach ($data['items'] as $entry) {
        $child = Element::create(
          [
            'type' => 'gallery_item',
            'name' => 'gallery_item',
          ]
        );
        $child->field_media->target_id = $entry['id'];
        $child->field_content->value = $entry['alt'];
        $child->parent->entity = $entity;
        $child->save();
        $entity->children->appendItem($child);
      }
      $entity->saveEdit();
    }
  }

}
