<?php

namespace Drupal\acquia_contenthub_publisher\EventSubscriber\FilterFields;

use Drupal\acquia_contenthub_publisher\Libs\ExcludeSettingsInterface;
use Drupal\depcalc\DependencyCalculatorEvents;
use Drupal\depcalc\Event\FilterDependencyCalculationFieldsEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Removes dependency on excluded fields.
 *
 * @package Drupal\acquia_contenthub_publisher\EventSubscriber\FilterFields
 */
class RemoveExcludedFieldsDependencies implements EventSubscriberInterface {

  /**
   * The exclude field settings.
   *
   * @var \Drupal\acquia_contenthub_publisher\Libs\ExcludeSettingsInterface
   */
  protected ExcludeSettingsInterface $excludeSettings;

  /**
   * Constructor for the RemoveExcludedFieldsDependencies class.
   *
   * @param \Drupal\acquia_contenthub_publisher\Libs\ExcludeSettingsInterface $exclude_settings
   *   Exclude fields settings.
   */
  public function __construct(ExcludeSettingsInterface $exclude_settings) {
    $this->excludeSettings = $exclude_settings;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    $events[DependencyCalculatorEvents::FILTER_FIELDS][] = [
      'onFilterFields',
      1001,
    ];
    return $events;
  }

  /**
   * Filter excluded fields.
   *
   * @param \Drupal\depcalc\Event\FilterDependencyCalculationFieldsEvent $event
   *   Filter Dependency Calculation Fields.
   */
  public function onFilterFields(FilterDependencyCalculationFieldsEvent $event): void {
    $excluded_fields = $this->excludeSettings->getExcludedFields($event->getEntity()->getEntityTypeId(), $event->getEntity()->bundle());
    if (empty($excluded_fields)) {
      return;
    }
    $fields = array_filter($event->getFields(), function ($field) use ($excluded_fields) {
      return !in_array($field->getName(), $excluded_fields);
    });

    $event->setFields(...$fields);
  }

}
