<?php

namespace Drupal\languagewire_translation_provider\Adapter\Entity;

use Drupal\Core\Entity\EntityInterface as DrupalEntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\languagewire_translation_provider\Adapter\SystemInterface;
use Psr\Log\LoggerInterface;

/**
 * Drupal Entity Repository adapter.
* */
final class EntityRepository implements EntityRepositoryInterface {

  /**
   * Logger.
   *
   * @var \Psr\Log\LoggerInterface
   */
  private LoggerInterface $logger;

  /**
   * Entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  private EntityTypeManagerInterface $entityTypeManager;

  /**
   * Constructs a new EntityRepository object.
   *
   * @param \Drupal\languagewire_translation_provider\Adapter\SystemInterface $system
   *   System.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   Entity type manager.
   */
  public function __construct(SystemInterface $system, EntityTypeManagerInterface $entityTypeManager) {
    $this->logger = $system->logger();
    $this->entityTypeManager = $entityTypeManager;
  }

  /**
   * {@inheritDoc}
   */
  public function getEntity(string $entityTypeId, string $entityId): ?EntityInterface {
    $entity = $this->load($entityTypeId, $entityId);
    return $entity ? new Entity($entity) : NULL;
  }

  /**
   * Load entity object.
   *
   * @param string $entityTypeId
   *   The entity type id.
   * @param string $entityId
   *   The entity id.
   *
   * @return \Drupal\Core\Entity\EntityInterface|null
   *   The entity object or null if not found.
   */
  private function load(string $entityTypeId, string $entityId): ?DrupalEntityInterface {
    try {
      return $this->entityTypeManager->getStorage($entityTypeId)->load($entityId);
    }
    catch (\Exception $exception) {
      $exceptionMessage = "Exception occurred when trying to load \"$entityId\" (ID $entityId) entity. \n $exception";
      $this->logger->warning($exceptionMessage);
      return NULL;
    }
  }

}
