<?php

namespace Drupal\lingotek\Plugin\Action;

use Drupal\lingotek\Exception\LingotekApiException;
use Drupal\lingotek\Exception\LingotekContentEntityStorageException;
use Drupal\lingotek\Exception\LingotekDocumentNotFoundException;
use Drupal\lingotek\Lingotek;

/**
 * Assigns ownership of a node to a user.
 *
 * @Action(
 *   id = "entity:lingotek_download_translations_action",
 *   action_label = @Translation("Download all @entity_label translations from Lingotek"),
 *   category = "Lingotek",
 *   deriver = "Drupal\lingotek\Plugin\Action\Derivative\ContentEntityLingotekActionDeriver",
 * )
 */
class DownloadAllTranslationsFromLingotekAction extends LingotekContentEntityActionBase {

  /**
   * {@inheritdoc}
   */
  public function execute($entity = NULL) {
    $result = FALSE;
    $entityTypeBundleInfo = \Drupal::service('entity_type.bundle.info');
    $bundleInfos = $entityTypeBundleInfo->getBundleInfo($entity->getEntityTypeId());
    if (!$entity->getEntityType()->isTranslatable() || !$bundleInfos[$entity->bundle()]['translatable']) {
      $this->messenger()->addWarning(t('Cannot download @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;
    }
    /** @var \Drupal\lingotek\LingotekConfigurationServiceInterface $lingotek_configuration */
    $lingotek_configuration = \Drupal::service('lingotek.configuration');
    if (!$lingotek_configuration->isEnabled($entity->getEntityTypeId(), $entity->bundle())) {
      $this->messenger()->addWarning(t('Cannot download @type %label. That @bundle_label is not enabled for Lingotek translation.',
        ['@type' => $bundleInfos[$entity->bundle()]['label'], '%label' => $entity->label(), '@bundle_label' => $entity->getEntityType()->getBundleLabel()]));
      return FALSE;
    }
    try {
      if ($this->translationService->isDownloadQueueEnabled()) {
        $queued_count = 0;
        $skipped_status_pairs = [];
        $source_langcode = $entity->getUntranslated()->language()->getId();
        $language_locale_mapper = \Drupal::service('lingotek.language_locale_mapper');
        foreach (\Drupal::languageManager()->getLanguages() as $langcode => $language) {
          if ($langcode === $source_langcode) {
            continue;
          }
          $current_status = $this->translationService->checkTargetStatus($entity, $langcode);
          if (!in_array($current_status, Lingotek::DOWNLOADABLE_STATUSES, TRUE)) {
            // Skip languages whose target is not in a downloadable state
            // (PENDING/REQUEST/UNTRACKED/LOCKED/DISABLED/CANCELLED). These
            // would always fail inside downloadDocument() and only add lock
            // contention + log noise.
            $skipped_status_pairs[] = $langcode . ':' . ($current_status === FALSE || $current_status === NULL ? 'NONE' : (string) $current_status);
            continue;
          }
          $locale = $language_locale_mapper->getLocaleForLangcode($langcode);
          if ($this->translationService->enqueueDownload($entity, $locale, ['source' => 'action_download_all'])) {
            $queued_count++;
          }
        }
        if ($skipped_status_pairs !== []) {
          \Drupal::logger('lingotek')->info('Download All (queue): entity @entity_type:@entity_id skipped @skipped_count non-downloadable target(s) (@summary); queued @queued_count.', [
            '@entity_type' => $entity->getEntityTypeId(),
            '@entity_id' => (string) $entity->id(),
            '@skipped_count' => (string) count($skipped_status_pairs),
            '@summary' => self::formatTargetStatusPairsForLog($skipped_status_pairs),
            '@queued_count' => (string) $queued_count,
          ]);
        }
        if ($queued_count > 0) {
          $this->messenger()->addStatus(t('Queued @count translation downloads for @entity_type %title.',
            ['@count' => $queued_count, '@entity_type' => $entity->getEntityTypeId(), '%title' => $entity->label()]));
          return TRUE;
        }
        $this->messenger()->addWarning(t('No translations were queued for @entity_type %title because none were ready to download.',
          ['@entity_type' => $entity->getEntityTypeId(), '%title' => $entity->label()]));
        return FALSE;
      }
      /** @var \Drupal\node\NodeInterface $entity */
      $result = $this->translationService->downloadDocuments($entity);
    }
    catch (LingotekDocumentNotFoundException $exc) {
      $this->messenger()
        ->addError(t('Document @entity_type %title was not found. Please upload again.', [
          '@entity_type' => $entity->getEntityTypeId(),
          '%title' => $entity->label(),
        ]));
    }
    catch (LingotekApiException $exception) {
      $this->messenger()->addError(t('The download for @entity_type %title translation failed. Please try again.', ['@entity_type' => $entity->getEntityTypeId(), '%title' => $entity->label()]));
    }
    catch (LingotekContentEntityStorageException $storage_exception) {
      if ($storage_exception->isLockTimeout()) {
        \Drupal::logger('lingotek')->error('The download for @entity_type %title failed because another translation save is in progress (database lock timeout).',
          ['@entity_type' => $entity->getEntityTypeId(), '%title' => $entity->label()]);
        $this->messenger()->addError(t('The download for @entity_type %title could not be completed because another translation save is in progress. Please retry in a moment.',
          ['@entity_type' => $entity->getEntityTypeId(), '%title' => $entity->label()]));
      }
      elseif ($storage_exception->isFieldTooLongError()) {
        \Drupal::logger('lingotek')->error('The download for @entity_type %title failed because of the length of one field translation value: %table.',
          ['@entity_type' => $entity->getEntityTypeId(), '%title' => $entity->label(), '%table' => $storage_exception->getTable()]);
        $this->messenger()->addError(t('The download for @entity_type %title failed because of the length of one field translation value: %table.',
          ['@entity_type' => $entity->getEntityTypeId(), '%title' => $entity->label(), '%table' => $storage_exception->getTable()]));
      }
      else {
        \Drupal::logger('lingotek')->error('The download for @entity_type %title failed due to a storage error while saving translated content.',
          ['@entity_type' => $entity->getEntityTypeId(), '%title' => $entity->label()]);
        $this->messenger()->addError(t('The download for @entity_type %title failed while saving translated content. Please retry.',
          ['@entity_type' => $entity->getEntityTypeId(), '%title' => $entity->label()]));
      }
    }
    return $result;
  }

  /**
   * Builds a short comma-separated summary for watchdog (length-capped).
   *
   * @param string[] $pairs
   *   Each element like "fr:PENDING".
   *
   * @return string
   *   Safe for a single log line; truncates to avoid oversized DB rows.
   */
  private static function formatTargetStatusPairsForLog(array $pairs): string {
    $max_entries = 12;
    $max_length = 500;
    $slice = array_slice($pairs, 0, $max_entries);
    $out = implode(',', $slice);
    if (count($pairs) > $max_entries) {
      $out .= ',...+' . (count($pairs) - $max_entries) . ' more';
    }
    if (strlen($out) > $max_length) {
      return substr($out, 0, $max_length - 3) . '...';
    }
    return $out;
  }

}
