<?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\Exception\StrakerTranslateDocumentLockedException;
use Drupal\straker_translate\Exception\StrakerTranslateDocumentAlreadyUploaded;
use Drupal\straker_translate\Exception\StrakerTranslatePaymentRequiredException;
use Drupal\straker_translate\Exception\StrakerTranslateProcessedWordsLimitException;
use Drupal\straker_translate\FormComponent\StrakerTranslateFormComponentBulkActionBase;
use Drupal\straker_translate\FormComponent\StrakerTranslateFormComponentBulkActionExecutor;
use Drupal\straker_translate\StrakerTranslateConfigurationServiceInterface;
use Drupal\straker_translate\StrakerTranslateContentTranslationServiceInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Defines a Straker Translate bulk action plugin for the forceful upload operation.
 *
 * @StrakerTranslateFormComponentBulkAction(
 *   id = "force_upload",
 *   title = @Translation("Re-upload document forcefully"),
 *   weight = 10,
 *   form_ids = {
 *     "straker_translate_management",
 *     "straker_translate_entity_management",
 *   },
 *   batch = {
 *     "title" = @Translation("Forcefully uploading content to Straker Translate service")
 *   }
 * )
 */
class ForceUpload extends StrakerTranslateFormComponentBulkActionBase {

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

  /**
   * 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\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, 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;
  }

  /**
   * {@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.configuration'),
      $container->get('straker_translate.content_translation'),
      $container->get('entity_type.bundle.info'),
    );
  }

  /**
   *
   */
  public function executeSingle(ContentEntityInterface $entity, $options, StrakerTranslateFormComponentBulkActionExecutor $executor, array &$context) {
    $context['message'] = $this->t('Forcefully uploading @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 forcefully upload @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 forcefully upload @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)) {
      try {
        if ($this->translationService->uploadDocument($entity, TRUE)) {
          $this->messenger()->addStatus(t('@entity_type %title has been Re-uploaded successfully.', ['@entity_type' => ucfirst($entity->getEntityTypeId()), '%title' => $entity->label()]));
        }
        else {
          $this->messenger()->addError(t('The forceful upload for @entity_type %title failed. Check your configuration and profile and try again.', ['@entity_type' => $entity->getEntityTypeId(), '%title' => $entity->label()]));
        }
      }
      catch (StrakerTranslateDocumentAlreadyUploaded $exc) {
        // This catch block is kept for consistency but should ideally not be reached
        // if the getDocumentId() check works as expected.
        $this->messenger()->addWarning($this->t('Document @entity_type %title was already uploaded. Skipping forceful upload (via exception).', ['@entity_type' => $entity->getEntityTypeId(), '%title' => $entity->label()]));
        return FALSE;
      }
      catch (StrakerTranslatePaymentRequiredException $exception) {
        $this->messenger()->addError($this->t('Community has been disabled. Please contact support@straker_translate.com to re-enable your community.'));
        return FALSE;
      }
      catch (StrakerTranslateDocumentLockedException $exception) {
        $this->messenger()->addError($this->t('Document @entity_type %title has a new version. The document id has been updated for all future interactions. Please try again.', ['@entity_type' => $entity->getEntityTypeId(), '%title' => $entity->label()]));
        return FALSE;
      }
      catch (StrakerTranslateProcessedWordsLimitException $exception) {
        $this->messenger()->addError($this->t('Processed word limit exceeded. Please contact your local administrator or Straker Translate Client Success (<a href=":link">@mail</a>) for assistance.', [':link' => 'mailto:sales@straker_translate.com', '@mail' => 'sales@straker_translate.com']));
        return FALSE;
      }
      catch (StrakerTranslateApiException $exception) {
        if ($this->translationService->getDocumentId($entity)) {
          $this->messenger()->addError($this->t('The forceful update for @entity_type %title failed. Please try again.', ['@entity_type' => $entity->getEntityTypeId(), '%title' => $entity->label()]));
        }
        else {
          $this->messenger()->addError($this->t('The forceful upload for @entity_type %title 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;
  }

}
