<?php

namespace Drupal\languagewire_translation_provider\Platform;

use Drupal\languagewire_translation_provider\Client\ClientInterface;
use Drupal\languagewire_translation_provider\Client\Product;
use Drupal\languagewire_translation_provider\Platform\Services\HumanAssistedMachineTranslation;
use Drupal\languagewire_translation_provider\Platform\Services\HumanTranslation;
use Drupal\languagewire_translation_provider\Platform\Services\MachineTranslation;
use Drupal\languagewire_translation_provider\Platform\Services\ServiceInterface;

/**
 * Available Services.
 */
final class AvailableServices {
  public const MACHINE_TRANSLATION_SERVICE_ID = 21;
  public const POST_EDITED_MACHINE_TRANSLATION_SERVICE_ID = 22;
  public const POST_EDITED_MACHINE_TRANSLATION_WITH_VALIDATION_SERVICE_ID = 23;

  /**
   * Client.
   *
   * @var \Drupal\languagewire_translation_provider\Client\ClientInterface
   */
  private ClientInterface $client;

  /**
   * Constructs a new AvailableServices object.
   *
   * @param \Drupal\languagewire_translation_provider\Client\ClientInterface $client
   *   Client.
   */
  public function __construct(ClientInterface $client) {
    $this->client = $client;
  }

  /**
   * Get.
   */
  public function get(): \Generator {
    foreach ($this->client->getProducts() as $product) {
      yield $this->createService($product);
    }
  }

  /**
   * Get by id.
   */
  public function getById(int $serviceId): ?ServiceInterface {
    foreach ($this->get() as $service) {
      if ($service->id() == $serviceId) {
        return $service;
      }
    }

    return NULL;
  }

  /**
   * Create service.
   */
  private function createService(Product $product): ServiceInterface {
    return match ($product->id()) {
      self::MACHINE_TRANSLATION_SERVICE_ID => new MachineTranslation($product->id(), $product->name(), new MachineTranslationLanguages()),
      self::POST_EDITED_MACHINE_TRANSLATION_SERVICE_ID, self::POST_EDITED_MACHINE_TRANSLATION_WITH_VALIDATION_SERVICE_ID => new HumanAssistedMachineTranslation($product->id(), $product->name(), new MachineTranslationLanguages()),
      default => new HumanTranslation($product->id(), $product->name(), new AllLanguages()),
    };
  }

}
