<?php

namespace Drupal\straker_translate\Plugin\StrakerTranslateFormComponent\BulkAction;

use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\straker_translate\Exception\StrakerTranslateApiException;
use Drupal\straker_translate\FormComponent\StrakerTranslateFormComponentBulkActionBase;
use Drupal\straker_translate\FormComponent\StrakerTranslateFormComponentBulkActionExecutor;
use Drupal\straker_translate\LanguageLocaleMapperInterface;
use Drupal\straker_translate\StrakerTranslateConfigurationServiceInterface;
use Drupal\straker_translate\StrakerTranslateContentTranslationServiceInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\straker_translate\Exception\StrakerTranslateDocumentAlreadyUploaded;

/**
 * Defines a Straker Translate bulk action plugin for the request all translations
 * operation.
 *
 * @StrakerTranslateFormComponentBulkAction(
 *   id = "download_translations",
 *   title = @Translation("Download all translations"),
 *   group = @Translation("Download translations"),
 *   weight = 75,
 *   form_ids = {
 *     "straker_translate_management",
 *     "straker_translate_entity_management",
 *   },
 *   batch = {
 *     "title" = @Translation("Downloading translations from the Straker Translate service."),
 *     "function" = "createBatch"
 *   }
 * )
 */
class DownloadTranslations extends StrakerTranslateFormComponentBulkActionBase {

  /**
   * The entity type bundle info service.
   *
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $entityTypeBundleInfo;

  /**
   * The language-locale mapper.
   *
   * @var \Drupal\straker_translate\LanguageLocaleMapperInterface
   */
  protected $languageLocaleMapper;

  /**
   * DebugExport constructor.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity_type.manager service.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language_manager service.
   * @param \Drupal\straker_translate\LanguageLocaleMapperInterface $language_locale_mapper
   *   The language-locale mapper.
   * @param \Drupal\straker_translate\StrakerTranslateConfigurationServiceInterface $straker_translate_configuration
   *   The straker_translate.configuration service.
   * @param \Drupal\straker_translate\StrakerTranslateContentTranslationServiceInterface $translation_service
   *   The straker_translate.content_translation service.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
   *   The entity_type.bundle.info service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, LanguageManagerInterface $language_manager, LanguageLocaleMapperInterface $language_locale_mapper, StrakerTranslateConfigurationServiceInterface $straker_translate_configuration, StrakerTranslateContentTranslationServiceInterface $translation_service, EntityTypeBundleInfoInterface $entity_type_bundle_info) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $language_manager, $straker_translate_configuration, $translation_service);
    $this->entityTypeBundleInfo = $entity_type_bundle_info;
    $this->languageLocaleMapper = $language_locale_mapper;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity_type.manager'),
      $container->get('language_manager'),
      $container->get('straker_translate.language_locale_mapper'),
      $container->get('straker_translate.configuration'),
      $container->get('straker_translate.content_translation'),
      $container->get('entity_type.bundle.info'),
    );
  }

  /**
   *
   */
  public function createBatch(StrakerTranslateFormComponentBulkActionExecutor $executor, array $entities, array $options) {
    $plugin_manager = \Drupal::service('plugin.manager.straker_translate_form_bulk_action');
    // We can pass any valid value, as if we reach this we have a valid form id
    // already.
    $plugins = $plugin_manager->getApplicable(['form_id' => 'straker_translate_management']);
    // If that preference is active, we use the action for each language
    // independently.
    $split_download_all = $this->straker_translateConfiguration->getPreference('split_download_all');
    $operations = [];
    if ($split_download_all) {
      foreach ($entities as $entity) {
        $languages = $this->straker_translateConfiguration->getEnabledLanguages();
        foreach ($languages as $langcode => $language) {
          if (isset($plugins['download_translation:' . $langcode])) {
            $operations[] = [
              [
                $executor,
                'doExecuteSingle',
              ],
              [$plugins['download_translation:' . $langcode], $entity, $options, $plugins['upload'] ?? NULL],
            ];
          }
        }
      }
      $batch = [
        'title' => $this->getPluginDefinition()['batch']['title'],
        'operations' => $operations,
        'finished' => [$this, 'finished'],
        'progressive' => TRUE,
      ];
      batch_set($batch);
    }
    else {
      foreach ($entities as $entity) {
        $operations[] = [[$this, 'executeSingle'], [$entity, $options, $executor]];
      }
      $batch = [
        'title' => $this->getTitle(),
        'operations' => $operations,
        'finished' => [$this, 'finished'],
        'progressive' => TRUE,
      ];
      batch_set($batch);
      return TRUE;
    }
  }

  /**
   *
   */
  public function executeSingle(ContentEntityInterface $entity, array $options, StrakerTranslateFormComponentBulkActionExecutor $executor, array &$context) {
    $context['message'] = $this->t('Downloading all translations for @type %label.', ['@type' => $entity->getEntityType()->getLabel(), '%label' => $entity->label()]);
    $bundleInfos = $this->entityTypeBundleInfo->getBundleInfo($entity->getEntityTypeId());
    if (!$entity->getEntityType()->isTranslatable() || !$bundleInfos[$entity->bundle()]['translatable']) {
      $this->messenger()->addWarning($this->t('Cannot download translations for @type %label. That @bundle_label is not enabled for translation.',
        ['@type' => $bundleInfos[$entity->bundle()]['label'], '%label' => $entity->label(), '@bundle_label' => $entity->getEntityType()->getBundleLabel()]));
      return FALSE;
    }
    if (!$this->straker_translateConfiguration->isEnabled($entity->getEntityTypeId(), $entity->bundle())) {
      $this->messenger()->addWarning($this->t('Cannot download translations for @type %label. That @bundle_label is not enabled for Straker translation.',
        ['@type' => $bundleInfos[$entity->bundle()]['label'], '%label' => $entity->label(), '@bundle_label' => $entity->getEntityType()->getBundleLabel()]
      ));
      return FALSE;
    }
    if ($profile = $this->straker_translateConfiguration->getEntityProfile($entity)) {
      $languages = $this->languageManager->getLanguages();
      foreach ($languages as $langcode => $language) {
        if ($langcode !== $entity->language()->getId()) {
          try {
            $file_id = $this->translationService->getTargetFileId($entity, $langcode);
            if ($file_id) {
              $success = $this->translationService->downloadDocument($entity, $file_id, $langcode);
              if (!$success) {
                $this->messenger()->addError(t('The download for @entity_type %title translation failed. Check the logs and try again.', ['@entity_type' => $entity->getEntityTypeId(), '%title' => $entity->label()]));
                return FALSE;
              }
              else {
                $this->messenger()->addStatus(t('@entity_type %title translation for %language has been downloaded.', ['@entity_type' => ucfirst($entity->getEntityTypeId()), '%title' => $entity->label(), '%language' => $langcode]));
              }
            }
            else {
              $this->messenger()->addWarning($this->t('No translation file found for @entity_type %title translation in %language.', ['@entity_type' => $entity->getEntityTypeId(), '%title' => $entity->label(), '%language' => $langcode]));
            }
          }
          catch (StrakerTranslateDocumentAlreadyUploaded $exc) {
            $this->messenger()->addWarning($this->t('The document for @entity_type %title has already been downloaded and processed or is current.', ['@entity_type' => $entity->getEntityTypeId(), '%title' => $entity->label()]));
            return FALSE;
          }
          catch (StrakerTranslateApiException $exception) {
            $this->messenger()->addError($this->t('The download for @entity_type %title translation failed. Please try again.', [
              '@entity_type' => $entity->getEntityTypeId(),
              '%title' => $entity->label(),
            ]));
            return FALSE;
          }
        }
      }
    }
    else {
      $this->messenger()->addWarning($this->t('The @type %label has no profile assigned so it was not processed.',
        ['@type' => $bundleInfos[$entity->bundle()]['label'], '%label' => $entity->label()]));
      return FALSE;
    }
    return TRUE;
  }

}
