<?php

namespace Drupal\straker_translate\Controller;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\straker_translate\Exception\StrakerTranslateApiException;
use Drupal\straker_translate\Exception\StrakerTranslateDocumentArchivedException;
use Drupal\straker_translate\Exception\StrakerTranslateDocumentLockedException;
use Drupal\straker_translate\Exception\StrakerTranslateDocumentNotFoundException;
use Drupal\straker_translate\Exception\StrakerTranslatePaymentRequiredException;
use Drupal\straker_translate\Exception\StrakerTranslateProcessedWordsLimitException;
use Drupal\straker_translate\LanguageLocaleMapperInterface;
use Drupal\straker_translate\StrakerTranslateInterface;
use Drupal\straker_translate\StrakerTranslateInterfaceTranslationServiceInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 *
 */
class StrakerTranslateInterfaceTranslationController extends StrakerTranslateControllerBase {

  /**
   * The Straker Translate interface translation service.
   *
   * @var \Drupal\straker_translate\StrakerTranslateInterfaceTranslationServiceInterface
   */
  protected $straker_translateInterfaceTranslation;

  /**
   * Constructs a StrakerTranslateManagementController object.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The Request instance.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\straker_translate\StrakerTranslateInterface $straker_translate
   *   The straker_translate service.
   * @param \Drupal\straker_translate\LanguageLocaleMapperInterface $language_locale_mapper
   *   The language-locale mapper.
   * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
   *   The form builder.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\straker_translate\StrakerTranslateInterfaceTranslationServiceInterface $straker_translate_interface_translation
   *   The Straker Translate interface translation service.
   */
  public function __construct(Request $request, ConfigFactoryInterface $config_factory, StrakerTranslateInterface $straker_translate, LanguageLocaleMapperInterface $language_locale_mapper, FormBuilderInterface $form_builder, LoggerInterface $logger, StrakerTranslateInterfaceTranslationServiceInterface $straker_translate_interface_translation) {
    parent::__construct($request, $config_factory, $straker_translate, $language_locale_mapper, $form_builder, $logger);
    $this->straker_translateInterfaceTranslation = $straker_translate_interface_translation;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('request_stack')->getCurrentRequest(),
      $container->get('config.factory'),
      $container->get('straker_translate'),
      $container->get('straker_translate.language_locale_mapper'),
      $container->get('form_builder'),
      $container->get('logger.channel.straker_translate'),
      $container->get('straker_translate.interface_translation')
    );
  }

  /**
   *
   */
  public function upload(Request $request) {
    $component = $request->query->get('component');
    \Drupal::logger('straker_translate')->info('Upload called with component: @component', ['@component' => $component]);

    if ($component) {
      // It is not a config entity, but a config object.
      if ($this->straker_translateInterfaceTranslation->getDocumentId($component)) {
        \Drupal::logger('straker_translate')->info('Document ID found, redirecting to update');
        return $this->update($request);
      }
      else {
        try {
          \Drupal::logger('straker_translate')->info('Attempting to upload document for component: @component', ['@component' => $component]);
          if ($this->straker_translateInterfaceTranslation->uploadDocument($component)) {
            $this->messenger()->addStatus($this->t('%label uploaded successfully', ['%label' => $component]));
          }
        }
        catch (StrakerTranslateDocumentArchivedException $exception) {
          $this->messenger()->addWarning($this->t('Document %label has been archived. Uploading again.',
            ['%label' => $component]));
          return $this->upload($request);
        }
        catch (StrakerTranslateDocumentLockedException $exception) {
          $this->messenger()->addError($this->t('Document %label has a new version. The document id has been updated for all future interactions. Please try again.',
            ['%label' => $component]));
        }
        catch (StrakerTranslatePaymentRequiredException $exception) {
          $this->messenger()->addError($this->t('Community has been disabled. Please contact support@straker_translate.com to re-enable your community.'));
        }
        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']));
        }
        catch (StrakerTranslateApiException $e) {
          // Mark the document as failed.
          \Drupal::logger('straker_translate')->error('Upload failed with API exception: @message', ['@message' => $e->getMessage()]);
          $this->messenger()->addError($this->t('The upload for %label failed. Please try again.',
            ['%label' => $component]));
        }
        catch (\Exception $e) {
          // Catch any other exceptions
          \Drupal::logger('straker_translate')->error('Upload failed with unexpected exception: @message', ['@message' => $e->getMessage()]);
          $this->messenger()->addError($this->t('The upload for %label failed with an unexpected error. Please try again.',
            ['%label' => $component]));
        }
      }
    }
    else {
      \Drupal::logger('straker_translate')->warning('Upload called without component parameter');
    }

    // Get the destination from the query parameters or fall back to the interface translation page
    $destination = $request->query->get('destination');
    if (!$destination) {
      $destination = '/admin/straker-translate/manage/interface-translation';
    }

    return new RedirectResponse($destination);
  }

  /**
   *
   */
  public function update(Request $request) {
    $component = $request->query->get('component');
    if ($component) {
      try {
        if ($this->straker_translateInterfaceTranslation->uploadDocument($component)) {
          $this->messenger()->addStatus($this->t('%label has been updated.', ['%label' => $component]));
        }
      }
      catch (StrakerTranslateDocumentArchivedException $exception) {
        $this->messenger()->addWarning($this->t('Document %label has been archived. Uploading again.', ['%label' => $component]));
        return $this->upload($request);
      }
      catch (StrakerTranslateDocumentLockedException $exception) {
        $this->messenger()->addError($this->t('Document %label has a new version. The document id has been updated for all future interactions. Please try again.',
          ['%label' => $component]));
      }
      catch (StrakerTranslatePaymentRequiredException $exception) {
        $this->messenger()->addError($this->t('Community has been disabled. Please contact support@straker_translate.com to re-enable your community.'));
      }
      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']));
      }
      catch (StrakerTranslateApiException $e) {
        $this->messenger()->addError($this->t('%label update failed. Please try again.',
          ['%label' => $component]));
      }
    }
    return new RedirectResponse($request->getRequestUri());
  }

  /**
   *
   */
  public function checkUpload(Request $request) {
    $component = $request->query->get('component');
    if ($component) {
      try {
        if ($this->straker_translateInterfaceTranslation->checkSourceStatus($component)) {
          $this->messenger()->addStatus($this->t('The import for %label is complete.', ['%label' => $component]));
        }
        else {
          $this->messenger()->addStatus($this->t('The import for %label is still pending.', ['%label' => $component]));
        }
      }
      catch (StrakerTranslateDocumentNotFoundException $exc) {
        $this->messenger()->addError(t('Document %label was not found. Please upload again.', ['%label' => $component]));
      }
      catch (StrakerTranslateApiException $e) {
        $this->messenger()->addError($this->t('%label status check failed. Please try again.',
          ['%label' => $component]));
      }
    }
    return new RedirectResponse($request->getRequestUri());
  }

  /**
   *
   */
  public function download(Request $request) {
    $component = $request->query->get('component');
    $langcode = $request->query->get('locale');
    if ($component && $langcode) {
      try {
        if ($this->straker_translateInterfaceTranslation->downloadDocument($component, $langcode)) {
          $this->messenger()->addStatus($this->t('The translation of %label into @langcode has been downloaded.', ['@langcode' => $langcode, '%label' => $component]));
        }
        else {
          $this->messenger()->addStatus($this->t("The '@langcode' translation download for %label failed. Please try again.", ['@langcode' => $langcode, '%label' => $component]));
        }
      }
      catch (StrakerTranslateDocumentNotFoundException $exception) {
        $this->messenger()->addError($this->t('Document %label was not found. Please upload again.',
          ['%label' => $component]));
      }
      catch (StrakerTranslateDocumentArchivedException $exception) {
        $this->messenger()->addWarning($this->t('Document %label has been archived. Uploading again.',
          ['%label' => $component]));
        return $this->upload($request);
      }
      catch (StrakerTranslateDocumentLockedException $exception) {
        $this->messenger()->addError($this->t('Document %label has a new version. The document id has been updated for all future interactions. Please try again.',
          ['%label' => $component]));
      }
      catch (StrakerTranslatePaymentRequiredException $exception) {
        $this->messenger()->addError($this->t('Community has been disabled. Please contact support@straker_translate.com to re-enable your community.'));
      }
      catch (StrakerTranslateApiException $e) {
        $this->messenger()->addError($this->t("The '@langcode' translation download for %label failed. Please try again.",
          ['%label' => $component, '@langcode' => $langcode]));
      }
    }
    return new RedirectResponse($request->getRequestUri());
  }

}
