<?php

namespace Drupal\acquia_contenthub_subscriber\EventSubscriber\ParseCdf;

use Drupal\acquia_contenthub\Event\ParseCdfEntityEvent;
use Drupal\acquia_contenthub_subscriber\ContentHubSubscriberEvents;
use Drupal\acquia_contenthub_subscriber\Event\ViewFilterPluginReplaceEntityUuidWithIdEvent;
use Drupal\Core\Language\LanguageInterface;

/**
 * Replaces entity uuid with entity id in view filters.
 *
 * @see \Drupal\acquia_contenthub_publisher\EventSubscriber\Cdf\ViewFiltersCreateCdfEntityHandler
 *   The serializer of the view filter plugin.
 * @see \Drupal\acquia_contenthub_subscriber\ContentHubSubscriberEvents::REPLACE_ENTITY_UUID_WITH_ID
 */
class ViewFiltersParseCdfHandler extends ConvertEntityUuidToIdParseCdfBase {

  /**
   * Replace entity uuid with entity id in view filters.
   *
   * @param \Drupal\acquia_contenthub\Event\ParseCdfEntityEvent $event
   *   The parse cdf entity event.
   *
   * @throws \Exception
   */
  public function replaceEntityUuidWithId(ParseCdfEntityEvent $event): void {
    $cdf = $event->getCdf();
    $entity_type_id = $cdf->getAttribute('entity_type')->getValue()[LanguageInterface::LANGCODE_NOT_SPECIFIED];

    if ($entity_type_id !== 'view') {
      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 ($filters = $display_data['display_options']['filters'] ?? []) {
          $metadata_data[$lang]['display'][$display_name]['display_options']['filters'] =
            $this->getUpdatedFilterValuesWithEntityId($filters);
        }
      }
    }
    $this->updateMetadata($event, $metadata_data);
  }

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

}
