<?php

namespace Drupal\acquia_contenthub\EventSubscriber\GetSettings;

use Acquia\ContentHubClient\Settings;
use Drupal\acquia_contenthub\AcquiaContentHubEvents;
use Drupal\acquia_contenthub\Event\AcquiaContentHubSettingsEvent;
use Drupal\acquia_contenthub\Settings\ContentHubConfigurationInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Gets the ContentHub Server settings from configuration.
 */
class GetSettingsFromCoreConfig implements EventSubscriberInterface {

  /**
   * Core config provider.
   */
  public const PROVIDER = 'core_config';

  /**
   * The Config Factory.
   *
   * @var \Drupal\acquia_contenthub\Settings\ContentHubConfigurationInterface
   */
  protected ContentHubConfigurationInterface $achConfiguration;

  /**
   * GetSettingsFromCoreConfig constructor.
   *
   * @param \Drupal\acquia_contenthub\Settings\ContentHubConfigurationInterface $ach_configurations
   *   CH configuration factory.
   */
  public function __construct(ContentHubConfigurationInterface $ach_configurations) {
    $this->achConfiguration = $ach_configurations;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents(): array {
    $events[AcquiaContentHubEvents::GET_SETTINGS][] = 'onGetSettings';
    return $events;
  }

  /**
   * Extract settings from configuration and create a Settings object.
   *
   * @param \Drupal\acquia_contenthub\Event\AcquiaContentHubSettingsEvent $event
   *   The dispatched event.
   *
   * @see \Acquia\ContentHubClient\Settings
   */
  public function onGetSettings(AcquiaContentHubSettingsEvent $event) {
    $ch_connection = $this->achConfiguration->getConnectionDetails();
    $webhook = [
      'uuid' => $ch_connection->getWebhook('uuid'),
      'url' => $ch_connection->getWebhook('url'),
      'settings_url' => $ch_connection->getWebhook(),
    ];
    $settings = new Settings($ch_connection->getClientName(), $ch_connection->getClientUuid(), $ch_connection->getApiKey(), $ch_connection->getSecretKey(), $ch_connection->getHostname(), $ch_connection->getSharedSecret(), $webhook);
    if ($settings) {
      $event->setSettings($settings);
      $event->setProvider(self::PROVIDER);
      $event->stopPropagation();
    }
  }

}
