<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\languagewire_translation_provider\Adapter\SystemInterface;
use Drupal\languagewire_translation_provider\Adapter\TMGMT\TmgmtTranslator;
use Drupal\languagewire_translation_provider\Adapter\TMGMT\TranslatorRepositoryInterface;
use Drupal\languagewire_translation_provider\Platform\ConfigurationItemImporterFactory;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Platform configuration items controller.
 */
class PlatformConfigurationItemsController extends ControllerBase implements ContainerInjectionInterface {
  use StringTranslationTrait;

  /**
   * Configuration item importer factory.
   *
   * @var \Drupal\languagewire_translation_provider\Platform\ConfigurationItemImporterFactory
   */
  private ConfigurationItemImporterFactory $configurationItemImporterFactory;

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

  /**
   * Translator repository.
   *
   * @var \Drupal\languagewire_translation_provider\Adapter\TMGMT\TranslatorRepositoryInterface
   */
  private TranslatorRepositoryInterface $translatorRepository;

  /**
   * Constructs a new PlatformConfigurationItemsController object.
   *
   * @param \Drupal\languagewire_translation_provider\Platform\ConfigurationItemImporterFactory $configurationItemImporterFactory
   *   Configuration item importer factory.
   * @param \Drupal\languagewire_translation_provider\Adapter\SystemInterface $system
   *   System.
   * @param \Drupal\languagewire_translation_provider\Adapter\TMGMT\TranslatorRepositoryInterface $translatorRepository
   *   Translator repository.
   */
  public function __construct(
    ConfigurationItemImporterFactory $configurationItemImporterFactory,
    SystemInterface $system,
    TranslatorRepositoryInterface $translatorRepository
  ) {
    $this->configurationItemImporterFactory = $configurationItemImporterFactory;
    $this->logger = $system->logger();
    $this->translatorRepository = $translatorRepository;
  }

  /**
   * Refresh platform configuration items.
   */
  public function refreshPlatformConfigurationItems(Request $request): RedirectResponse {
    $tmgmtTranslatorName = $request->query->get('translator');

    if (empty($tmgmtTranslatorName)) {
      $this->messenger()->addError($this->t('No TMGMT translator ID provided.'));
      return new RedirectResponse("/admin/tmgmt/translators");
    }

    $tmgmtTranslator = $this->translatorRepository->getById($tmgmtTranslatorName);

    if ($tmgmtTranslator == NULL) {
      $this->messenger()->addError($this->t('Invalid TMGMT translator ID provided.'));
      return new RedirectResponse("/admin/tmgmt/translators");
    }

    try {
      $translatorAdapter = new TmgmtTranslator($tmgmtTranslator);
      $configurationItemImporter = $this->configurationItemImporterFactory->createFor($translatorAdapter);
      $configurationItemImporter->importItems($translatorAdapter);

      $tmgmtTranslator->save();

      $this->messenger()->addMessage($this->t('Platform configuration items have been refreshed.'));
      return new RedirectResponse("/admin/tmgmt/translators/manage/$tmgmtTranslatorName");
    }
    catch (\Exception $exception) {
      $this->logger->error("Failed to refresh platform configuration items: $exception");

      $this->messenger()->addError($this->t('Could not refresh platform configuration items. Please try again later.'));
      return new RedirectResponse("/admin/tmgmt/translators/manage/$tmgmtTranslatorName");
    }
  }

  /**
   * {@inheritdoc}
   *
   * @throws \Exception
   */
  public static function create(ContainerInterface $container): PlatformConfigurationItemsController {
    return new static(
          $container->get('languagewire.configuration_item_importer_factory') ?? throw new \Exception('Configuration item importer factory not found.'),
          $container->get('languagewire.drupal.system') ?? throw new \Exception('System not found.'),
          $container->get('languagewire.tmgmt_translator_repository') ?? throw new \Exception('Translator repository not found.')
      );
  }

}
