<?php

namespace Drupal\pagedesigner_gallery\Plugin\pagedesigner\Handler;

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

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

  /**
   * {@inheritdoc}
   */
  public function collectAttachments(array &$attachments) {
    $query = $this->entityTypeManager->getStorage('pagedesigner_element')
      ->getQuery()
      ->accessCheck(FALSE)
      ->condition('type', 'gallery_gallery');

    // Simulate COALESCE with OR condition.
    $deleted_condition = $query->orConditionGroup()
      ->condition('deleted', NULL, 'IS NULL')
      ->condition('deleted', 0);
    $query->condition($deleted_condition);

    $galleryIds = $query->execute();
    $galleries = [];
    foreach ($galleryIds as $id) {
      $gallery = Element::load($id);
      $galleries[$id] = $gallery->name->value;
    }
    $attachments['drupalSettings']['pagedesigner_gallery']['galleries'] = $galleries;
    $attachments['library'][] = 'pagedesigner_gallery/pagedesigner';
  }

  /**
   * {@inheritdoc}
   */
  public function serialize(Element $entity, array &$result = []) {
    $data = [];

    if ($entity->field_gallery->entity != NULL) {
      $data = [
        'id' => $entity->field_gallery->target_id,
        'name' => $entity->field_gallery->entity->name->value,
        'items' => $this->elementHandler->serialize($entity->field_gallery->entity),
      ];
    }
    $result = $data + $result;

  }

  /**
   * {@inheritdoc}
   */
  public function get(Element $entity, string &$result = '') {
    if ($entity->field_gallery->entity != NULL) {
      $result .= $this->elementHandler->get($entity->field_gallery->entity);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function build(Element $entity, string $view_mode, array &$build = []) {
    if ($entity->field_gallery->entity != NULL) {
      $build = $this->elementHandler->serialize($entity->field_gallery->entity) + $build;
      $this->renderer->addCacheableDependency($build, $entity->field_gallery->entity);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function generate($definition, array $data, ?Element &$entity = NULL) {
    $type = $definition['type'];
    $name = (!empty($definition['name'])) ? $definition['name'] : $definition['type'];
    $entity = Element::create([
      'type' => $type,
      'name' => $name,
      'parent' => ['target_id' => $data['parent']],
      'container' => ['target_id' => $data['container']],
      'field_placeholder' => ['value' => $data['placeholder']],
      'entity' => ['target_id' => $data['entity']],
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function patch(Element $entity, array $data) {
    if (\is_numeric($data['id'])) {
      $entity->field_gallery->target_id = $data['id'];
      $entity->field_gallery->entity->name->value = $data['name'];
      $entity->field_gallery->entity->save();
      $entity->saveEdit();
    }
    elseif ($data['id'] == NULL) {
      $entity->field_gallery->entity = Element::create([
        'type' => 'gallery_gallery',
        'name' => 'Gallery',
      ]);
      $entity->field_gallery->entity->save();
      if (empty($data['name'])) {
        $entity->field_gallery->entity->name->value .= ' ' . $entity->field_gallery->entity->id();
      }
      else {
        $entity->field_gallery->entity->name->value = $data['name'];
      }
      $entity->field_gallery->entity->save();
      $entity->saveEdit();
    }
    if ($entity->field_gallery->entity != NULL) {
      if (isset($data['items'])) {
        $this->elementHandler->patch($entity->field_gallery->entity, $data);
      }
    }
  }

}
