<?php

namespace Drupal\languagewire_translation_provider\Database;

use Drupal\languagewire_translation_provider\Adapter\Database\LanguageWireConfigurationItemRepositoryInterface;
use Drupal\languagewire_translation_provider\Adapter\TMGMT\TmgmtTranslatorInterface;
use Drupal\languagewire_translation_provider\Client\ConfigurationItemInterface;

/**
 * Configuration Item Repository Base.
 * */
abstract class TypedConfigurationItemRepositoryBase implements ConfigurationItemRepositoryInterface {
  /**
   * Configuration item repository.
   *
   * @var \Drupal\languagewire_translation_provider\Adapter\Database\LanguageWireConfigurationItemRepositoryInterface
   */
  private LanguageWireConfigurationItemRepositoryInterface $itemRepository;

  /**
   * Constructs a new TypedConfigurationItemRepositoryBase object.
   *
   * @param \Drupal\languagewire_translation_provider\Adapter\Database\LanguageWireConfigurationItemRepositoryInterface $itemRepository
   *   Configuration item repository.
   */
  public function __construct(LanguageWireConfigurationItemRepositoryInterface $itemRepository) {
    $this->itemRepository = $itemRepository;
  }

  /**
   * {@inheritDoc}
   */
  public function removeAll(TmgmtTranslatorInterface $translator): void {
    $this->itemRepository->removeAll($translator, $this->type());
  }

  /**
   * {@inheritDoc}
   */
  public function saveAll(array $items, TmgmtTranslatorInterface $translator): void {
    $this->itemRepository->saveAll($items, $translator, $this->type());
  }

  /**
   * {@inheritDoc}
   */
  public function getAll(TmgmtTranslatorInterface $translator): array {
    $items = $this->itemRepository->getAll($translator, $this->type());

    return array_map([$this, 'map'], $items);
  }

  /**
   * {@inheritDoc}
   */
  public function getById(int $itemId, TmgmtTranslatorInterface $translator): ?ConfigurationItemInterface {
    $item = $this->itemRepository->getByIdAndType($translator, $itemId, $this->type());

    return $item ? $this->map($item) : NULL;
  }

  /**
   * Get type.
   */
  abstract protected function type(): string;

  /**
   * Map.
   */
  abstract protected function map(\stdClass $configurationItem): ConfigurationItemInterface;

}
