<?php

namespace Drupal\straker_translate\Form;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Entity\EntityConstraintViolationListInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\straker_translate\LanguageLocaleMapperInterface;
use Drupal\straker_translate\StrakerTranslate;
use Drupal\straker_translate\StrakerTranslateContentTranslationServiceInterface;
use Drupal\straker_translate\StrakerTranslateSetupTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 *
 */
class StrakerTranslateMetadataEditForm extends ContentEntityForm {

  use StrakerTranslateSetupTrait;

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

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * The Straker Translate content translation service.
   *
   * @var \Drupal\straker_translate\StrakerTranslateContentTranslationServiceInterface
   */
  protected $translationService;

  /**
   * The entity type id.
   *
   * @var string
   */
  protected $entityTypeId;

  /**
   * Constructs a new StrakerTranslateManagementForm object.
   *
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   The entity repository.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
   *   The entity type bundle service.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The time service.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
   * @param \Drupal\straker_translate\LanguageLocaleMapperInterface $language_locale_mapper
   *   The language-locale mapper.
   * @param \Drupal\straker_translate\StrakerTranslateContentTranslationServiceInterface $translation_service
   *   The Straker Translate content translation service.
   * @param string $entity_type_id
   *   The entity type id.
   */
  public function __construct(EntityRepositoryInterface $entity_repository, EntityTypeBundleInfoInterface $entity_type_bundle_info, TimeInterface $time, LanguageManagerInterface $language_manager, LanguageLocaleMapperInterface $language_locale_mapper, StrakerTranslateContentTranslationServiceInterface $translation_service, ModuleHandlerInterface $module_handler, $entity_type_id) {
    parent::__construct($entity_repository, $entity_type_bundle_info, $time);

    $this->languageManager = $language_manager;
    $this->languageLocaleMapper = $language_locale_mapper;
    $this->translationService = $translation_service;
    $this->entityTypeId = $entity_type_id;

    $this->setModuleHandler($module_handler);

    $this->straker_translate = \Drupal::service('straker_translate');
    $this->operation = 'straker_translate_metadata';

    $entity = $this->getEntityFromRouteMatch($this->getRouteMatch(), $this->entityTypeId);
    $this->setEntity($entity);

  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity.repository'),
      $container->get('entity_type.bundle.info'),
      $container->get('datetime.time'),
      $container->get('language_manager'),
      $container->get('straker_translate.language_locale_mapper'),
      $container->get('straker_translate.content_translation'),
      $container->get('module_handler'),
      \Drupal::routeMatch()->getParameter('entity_type_id')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    if ($redirect = $this->checkSetup()) {
      return $redirect;
    }

    // $form = parent::buildForm($form, $form_state);
    /** @var \Drupal\straker_translate\Entity\StrakerTranslateContentMetadata  $entity */
    $entity = $this->getEntity();
    /** @var \Drupal\straker_translate\Entity\StrakerTranslateContentMetadata|NULL $metadata */
    $metadata = $entity->hasField('straker_translate_metadata') ? $entity->straker_translate_metadata->entity : NULL;
    $straker_translate_document_id = $this->translationService->getDocumentId($entity);
    $source_status = $this->translationService->getSourceStatus($entity);
    $form['metadata']['notice'] = [
      '#markup' => $this->t('Editing the metadata manually can cause diverse errors. If you find yourself using it often, please contact the module maintainers because you may have hit a bug.'),
      '#prefix' => '<span class="warning">',
      '#suffix' => '</span',
    ];
    $form['metadata']['straker_translate_document_id'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Straker Translate Document ID'),
      '#default_value' => $straker_translate_document_id,
    ];
    $default_langcode = $entity->getUntranslated()->language()->getId();
    $form['metadata']['straker_translate_source_status'] = [
      '#type' => 'select',
      '#title' => $this->t('Straker Translate Source Status: %langcode', ['%langcode' => $default_langcode]),
      '#default_value' => $source_status,
      '#options' => $this->getStrakerTranslateStatusesOptions(),
    ];
    $languages = $this->languageManager->getLanguages();
    $form['metadata']['straker_translate_target'] = [
      '#type' => 'container',
      '#tree' => TRUE,
    ];
    foreach ($languages as $langcode => $language) {
      if ($langcode === $default_langcode) {
        continue;
      }
      // Create a details element for each language if not already set.
      $form['metadata']['straker_translate_target'][$langcode] = [
        '#type' => 'fieldset',
        '#title' => $this->t('Target Language: %language', ['%language' => $language->getName()]),
      ];

      $form['metadata']['straker_translate_target'][$langcode]['status'] = [
        '#type' => 'select',
        '#title' => $this->t('Straker Translate Target Status'),
        '#default_value' => $this->translationService->getTargetStatus($entity, $langcode),
        '#options' => $this->getStrakerTranslateStatusesOptions(),
      ];
      $form['metadata']['straker_translate_target'][$langcode]['file_id'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Straker Translate Target File ID'),
        '#default_value' => $this->translationService->getTargetFileId($entity, $langcode),
      ];
    }
    $encodedMetadata = 'NULL';
    if ($metadata) {
      $encodedMetadata = json_encode($metadata->toArray(), JSON_PRETTY_PRINT);
    }
    $form['metadata']['verbatim_area'] = [
      '#type' => 'details',
      '#title' => $this->t('Straker Translate Verbatim Metadata'),
      "#collapsible" => TRUE,
      "#collapsed" => TRUE,
      '#tree' => TRUE,
      '#weight' => 50,
    ];
    $form['metadata']['verbatim_area']['verbatim'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Straker Translate Verbatim Metadata'),
      '#title_display' => 'invisible',
      '#readonly' => TRUE,
      '#cols' => '80',
      '#rows' => '20',
      '#default_value' => $encodedMetadata,
      '#attributes' => ['readonly' => TRUE],
    ];

    $form['actions'] = [];
    $form['actions']['save_metadata'] = [
      '#type' => 'submit',
      '#value' => t('Save metadata'),
      '#button_type' => 'primary',
      '#limit_validation_errors' => [],
      '#submit' => [[$this, 'saveMetadata']],
    ];
    return $form;
  }

  /**
   * Submit handler that saves the metadata of this content entity.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function saveMetadata(array &$form, FormStateInterface $form_state) {
    $entity = $this->getEntity();

    /** @var \Drupal\straker_translate\StrakerTranslateConfigurationServiceInterface $straker_translate_config */
    $straker_translate_config = \Drupal::service('straker_translate.configuration');

    if ($straker_translate_config->isEnabled($entity->getEntityTypeId(), $entity->bundle())) {
      $input = $form_state->getUserInput();
      $straker_translate_document_id = $input['straker_translate_document_id'];
      $source_status = $input['straker_translate_source_status'];
      $profile = $input['straker_translate_source_status'];
      $this->translationService->setDocumentId($entity, $straker_translate_document_id);
      $this->translationService->setSourceStatus($entity, $source_status);
      $target = $input["straker_translate_target"];
      foreach ($this->languageManager->getLanguages() as $langcode => $language) {
        if (isset($target[$langcode])) {
          $this->translationService->setTargetStatus($entity, $langcode, $target[$langcode]['status']);
          $this->translationService->setTargetFileId($entity, $langcode, $target[$langcode]['file_id']);
        }
      }
      /** @var \Drupal\straker_translate\Entity\StrakerTranslateContentMetadata|NULL $metadata */

      $this->messenger()->addStatus($this->t('Metadata saved successfully'));
    }
    else {
      $this->messenger()->addError($this->t('This entity cannot be managed in Straker Translate. Please check your configuration.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getBaseFormId() {
    return 'straker_translate_metadata_entity_form';
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    $form_id = $this->entityTypeId;
    $form_id .= '_' . $this->getBaseFormId();
    return $form_id;
  }

  /**
   *
   */
  public function getStrakerTranslateStatusesOptions() {
    return [
      StrakerTranslate::STATUS_CURRENT => $this->t('Current'),
      StrakerTranslate::STATUS_EDITED => $this->t('Edited'),
      StrakerTranslate::STATUS_IMPORTING => $this->t('Importing'),
      StrakerTranslate::STATUS_PROCESSING => $this->t('Processing'),
      StrakerTranslate::STATUS_PENDING => $this->t('Pending'),
      StrakerTranslate::STATUS_READY => $this->t('Ready'),
      StrakerTranslate::STATUS_REQUEST => $this->t('Request'),
      StrakerTranslate::STATUS_UNTRACKED => $this->t('Untracked'),
      StrakerTranslate::STATUS_CANCELLED => $this->t('Cancelled'),
      StrakerTranslate::STATUS_ERROR => $this->t('Error'),
    ];
  }

  /**
   * Form submission handler.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Not needed, we have our own handler.
  }

  /**
   *
   */
  protected function getEditedFieldNames(FormStateInterface $form_state) {
    return [];
  }

  /**
   *
   */
  protected function copyFormValuesToEntity(EntityInterface $entity, array $form, FormStateInterface $form_state) {
    // Do nothing. We don't want to alter the entity.
  }

  /**
   *
   */
  protected function flagViolations(EntityConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
    // @todo
    // We ignore violations.
  }

}
