<?php

namespace Drupal\straker_translate\Moderation;

/**
 * A facade for getting the services that are part of moderation integrations.
 *
 * @package Drupal\straker_translate\Moderation
 */
class StrakerTranslateModerationFactory implements StrakerTranslateModerationFactoryInterface {

  /**
   * The collected moderation config services.
   *
   * @var StrakerTranslateModerationConfigurationServiceInterface[]
   */
  protected $config;

  /**
   * The collected moderation form settings services.
   *
   * @var StrakerTranslateModerationSettingsFormInterface[]
   */
  protected $forms;

  /**
   * The collected moderation handler services.
   *
   * @var StrakerTranslateModerationHandlerInterface[]
   */
  protected $handlers;

  /**
   * Constructs a \Drupal\straker_translate\Moderation\StrakerTranslateModerationFactory object.
   */
  public function __construct() {
    $this->config = [];
    $this->forms = [];
    $this->handlers = [];
  }

  /**
   * {@inheritdoc}
   */
  public function addModerationConfiguration(StrakerTranslateModerationConfigurationServiceInterface $service, $id, $priority) {
    $this->config[$priority] = $service;
    krsort($this->config);
  }

  /**
   * {@inheritdoc}
   */
  public function addModerationForm(StrakerTranslateModerationSettingsFormInterface $service, $id, $priority) {
    $this->forms[$priority] = $service;
    krsort($this->forms);
  }

  /**
   * {@inheritdoc}
   */
  public function addModerationHandler(StrakerTranslateModerationHandlerInterface $service, $id, $priority) {
    $this->handlers[$priority] = $service;
    krsort($this->handlers);
  }

  /**
   * {@inheritdoc}
   */
  public function getModerationConfigurationService(): StrakerTranslateModerationConfigurationServiceInterface {
    $result = NULL;
    foreach ($this->config as $service) {
      if ($service->applies()) {
        $result = $service;
        break;
      }
    }
    return $result;
  }

  /**
   * {@inheritdoc}
   */
  public function getModerationSettingsForm(): StrakerTranslateModerationSettingsFormInterface {
    $result = NULL;
    foreach ($this->forms as $service) {
      if ($service->applies()) {
        $result = $service;
        break;
      }
    }
    return $result;
  }

  /**
   * {@inheritdoc}
   */
  public function getModerationHandler(): StrakerTranslateModerationHandlerInterface {
    $result = NULL;
    foreach ($this->handlers as $service) {
      if ($service->applies()) {
        $result = $service;
        break;
      }
    }
    return $result;
  }

}
