<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\Adapter\TMGMT;

use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\tmgmt\TranslatorInterface;
use function array_key_exists;

/**
 * Adapter on TMGMT translator.
* */
final class TmgmtTranslatorRepository implements TranslatorRepositoryInterface {
  /**
   * Entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  private EntityTypeManagerInterface $entityTypeManager;

  public function __construct(EntityTypeManagerInterface $entityTypeManager) {
    $this->entityTypeManager = $entityTypeManager;
  }

  /**
   * Get translator by ID.
   */
  public function getById(string $translatorId): ?TranslatorInterface {
    /** @var \Drupal\tmgmt\TranslatorInterface[] $translators */
    try {
      $translators = $this->entityTypeManager->getStorage('tmgmt_translator')->loadMultiple();
    }
    catch (InvalidPluginDefinitionException | PluginNotFoundException) {
      return NULL;
    }

    if (array_key_exists($translatorId, $translators)) {
      return $translators[$translatorId];
    }
    else {
      return NULL;
    }
  }

}
