<?php

namespace Drupal\acquia_contenthub_publisher\EventSubscriber\Cdf;

use Drupal\acquia_contenthub\Event\CreateCdfEntityEvent;
use Drupal\acquia_contenthub_publisher\ContentHubPublisherEvents;
use Drupal\acquia_contenthub_publisher\Event\ViewFilterPluginReplaceEntityIdWithUuidEvent;

/**
 * Handles entity id to uuid swap for view filter plugins.
 *
 * The entity is referenced through their id or not referenced at all, but
 * they are used in a numeric field as a hardcoded value.
 *
 * @see \Drupal\acquia_contenthub_subscriber\EventSubscriber\ParseCdf\ViewFiltersParseCdfHandler
 *   The unserializer of the view filter plugin.
 * @see \Drupal\acquia_contenthub_publisher\ContentHubPublisherEvents::REPLACE_ENTITY_ID_WITH_UUID
 */
class ViewFiltersCreateCdfEntityHandler extends ConvertEntityIdToUuidCreateCdfEntityBase {

  /**
   * Replace entity id with entity uuid.
   *
   * @param \Drupal\acquia_contenthub\Event\CreateCdfEntityEvent $event
   *   The create cdf entity event.
   */
  public function replaceEntityIdWithUuid(CreateCdfEntityEvent $event): void {
    if ($this->entity->getEntityTypeId() !== 'view') {
      return;
    }

    $cdf = $event->getCdf($this->entity->uuid());
    if (empty($cdf)) {
      return;
    }
    $metadata_data = $this->getDecodedMetadata($cdf);
    foreach ($metadata_data as $lang => $view) {
      if (empty($view['display'])) {
        continue;
      }
      foreach ($view['display'] as $display_name => $display_data) {
        if (!empty($display_data['display_options']['filters'])) {
          $metadata_data[$lang]['display'][$display_name]['display_options']['filters'] =
            $this->getUpdatedFilterValuesWithUuid($display_data['display_options']['filters']);
        }
      }
    }
    $this->updateMetadata($cdf, $metadata_data);
  }

  /**
   * Updates entity ids in filters with entity uuid.
   *
   * @param array $filters
   *   List of filters.
   *
   * @return array
   *   The updated  array of filters.
   */
  protected function getUpdatedFilterValuesWithUuid(array $filters): array {
    foreach ($filters as $filter_name => $filter_data) {
      if (empty($filter_data['plugin_id'])) {
        continue;
      }
      $event = new ViewFilterPluginReplaceEntityIdWithUuidEvent($filter_data, $filter_data['plugin_id']);
      $this->dispatcher->dispatch($event, ContentHubPublisherEvents::REPLACE_ENTITY_ID_WITH_UUID);
      $filters[$filter_name] = $event->getFilterData();
    }
    return $filters;
  }

}
