<?php

namespace Drupal\acquia_contenthub_publisher\Libs;

/**
 * An implementation of the exclude settings using drupal config.
 */
final class ExcludeSettings extends ConfigSettingsBase implements ExcludeSettingsInterface {

  /**
   * The name of the drupal configuration.
   */
  private const CONFIG_NAME = 'acquia_contenthub_publisher.exclude_settings';

  /**
   * {@inheritdoc}
   */
  public function getExcludedFields(string $entity_type_id, ?string $bundle_name = NULL): array {
    $data = $this->getConfig('excluded_fields');
    if (empty($entity_type_id) || empty($data[$entity_type_id])) {
      return [];
    }
    if (!empty($bundle_name)) {
      return $data[$entity_type_id][$bundle_name] ?? [];
    }
    return $data[$entity_type_id];
  }

  /**
   * {@inheritdoc}
   */
  public function excludeFields(string $entity_type_id, string $bundle_name, array $field_names): void {
    if (empty($entity_type_id) || empty($bundle_name)) {
      return;
    }
    $data = $this->values['excluded_fields'] ?? $this->getConfig('excluded_fields');
    $data[$entity_type_id][$bundle_name] = [];
    foreach ($field_names as $field_name) {
      $data[$entity_type_id][$bundle_name][] = $field_name;
    }
    $data[$entity_type_id] = array_filter($data[$entity_type_id]);
    $this->setConfig('excluded_fields', array_filter($data));
  }

  /**
   * {@inheritdoc}
   */
  public function removeExcludedFields(string $entity_type_id, string $bundle_name, array $field_names): bool {
    $data = $this->getConfig('excluded_fields');
    if (empty($data[$entity_type_id][$bundle_name])) {
      return FALSE;
    }
    $excluded_fields = $data[$entity_type_id][$bundle_name];
    $data[$entity_type_id][$bundle_name] = array_values(array_diff($excluded_fields, $field_names));
    $data[$entity_type_id] = array_filter($data[$entity_type_id]);
    $this->setConfig('excluded_fields', array_filter($data));
    $this->save();

    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function resetExcludedFields(): void {
    $this->setConfig('excluded_fields', []);
    $this->save();
  }

  /**
   * {@inheritdoc}
   */
  protected function getConfigName(): string {
    return self::CONFIG_NAME;
  }

}
