<?php

namespace Drupal\acquia_contenthub\EventSubscriber\UnserializeContentField;

use Drupal\acquia_contenthub\AcquiaContentHubEvents;
use Drupal\acquia_contenthub\Event\UnserializeCdfEntityFieldEvent;
use Drupal\Core\Entity\EntityInterface;
use Drupal\depcalc\DependencyStack;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Manual handling for text item fields filter references.
 */
class TextItemField extends FieldEntityReferenceBase implements EventSubscriberInterface {

  /**
   * Field types to unserialize.
   *
   * @var array
   */
  protected $fieldTypes = ['text_with_summary', 'text', 'text_long'];

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    $events[AcquiaContentHubEvents::UNSERIALIZE_CONTENT_ENTITY_FIELD] =
      ['onUnserializeContentField', 100];
    return $events;
  }

  /**
   * Extract the stored filter_format uuid and retrieve the entity id.
   *
   * @param \Drupal\acquia_contenthub\Event\UnserializeCdfEntityFieldEvent $event
   *   The unserialize event.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function onUnserializeContentField(UnserializeCdfEntityFieldEvent $event) {
    if (!in_array($event->getFieldMetadata()['type'], $this->fieldTypes)) {
      return;
    }

    $field = $event->getField();
    $values = [];

    // Return early if no attr values are set.
    if (empty($field['value'])) {
      return;
    }

    foreach ($field['value'] as $langcode => $value) {
      foreach ($value as &$item) {
        if (!$item['format']) {
          continue;
        }

        $filter = $this->getEntity($item['format'], $event, 'filter_format');
        if (!$filter) {
          $this->log($item['format']);
          $item['format'] = '';
          continue;
        }
        $item['format'] = $filter->id();
      }
      $values[$langcode][$event->getFieldName()] = $value;
    }
    $event->setValue($values);
    $event->stopPropagation();
  }

  /**
   * {@inheritdoc}
   */
  protected function getEntityByUuid(string $entity_type, string $uuid, DependencyStack $stack, string $field_name): ?EntityInterface {
    if ($stack->hasDependency($uuid)) {
      return $stack->getDependency($uuid)->getEntity();
    }

    $storage = \Drupal::entityTypeManager()->getStorage($entity_type);
    $entities = $storage->loadByProperties(['uuid' => $uuid]);
    return !empty($entities) ? reset($entities) : NULL;
  }

}
