<?php

namespace Drupal\straker_translate\Form;

use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\straker_translate\StrakerTranslateConfigurationServiceInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a common base class for Profile forms.
 */
class StrakerTranslateProfileFormBase extends EntityForm {

  /**
   * The Straker Translate configuration service.
   *
   * @var \Drupal\straker_translate\StrakerTranslateConfigurationServiceInterface
   */
  protected $straker_translateConfiguration;

  /**
   * Constructs a Straker Translate ProfileFormBase object.
   *
   * @param \Drupal\straker_translate\StrakerTranslateConfigurationServiceInterface $straker_translate_configuration
   *   The Straker Translate configuration service.
   */
  public function __construct(StrakerTranslateConfigurationServiceInterface $straker_translate_configuration) {
    $this->straker_translateConfiguration = $straker_translate_configuration;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('straker_translate.configuration'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'straker_translate_profile_add_form';
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
    /** @var \Drupal\straker_translate\StrakerTranslateProfileInterface $profile */
    $profile = $this->entity;
    $form['id'] = [
      '#type' => 'machine_name',
      '#description' => $this->t('A unique machine-readable name. Can only contain lowercase letters, numbers, and underscores.'),
      '#disabled' => !$profile->isNew(),
      '#default_value' => $profile->id(),
      '#machine_name' => [
        'exists' => '\Drupal\straker_translate\Entity\StrakerTranslateProfile::load',
        'source' => ['label'],
        'replace_pattern' => '([^a-z0-9_]+)|(^custom$)',
        'error' => $this->t('The machine-readable name must be unique, and can only contain lowercase letters, numbers, and underscores. Additionally, it can not be the reserved word "custom".'),
      ],
    ];
    $form['label'] = [
      '#id' => 'label',
      '#type' => 'textfield',
      '#title' => $this->t('Profile Name'),
      '#required' => TRUE,
      '#default_value' => $profile->label(),
    ];
    $form['current_future_note'] = [
      '#type' => 'markup',
      '#markup' => '<h3>' . $this->t('Profile settings impacting all entities (new and existing)') . '</h3><hr />',
    ];
    $form['auto_upload'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Upload Content Automatically'),
      '#description' => $this->t('When enabled, your Drupal content (including saved edits) will automatically be uploaded to Straker Translate for translation. When disabled, you are required to manually upload your content by clicking the "Upload" button on the Translations tab.'),
      '#disabled' => $profile->isLocked(),
      '#default_value' => $profile->hasAutomaticUpload(),
    ];
    $form['auto_download'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Download Translations Automatically'),
      '#description' => $this->t('When enabled, completed translation will automatically be downloaded from  Straker Translate. When disabled, you are required to manually download translations by clicking the "Download" button on the Translations tab.'),
      '#disabled' => $profile->isLocked(),
      '#default_value' => $profile->hasAutomaticDownload(),
    ];
    $form['auto_download_worker'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Use a Queue Worker to Download Translations'),
      '#description' => $this->t('When enabled, completed translation will automatically be queued for download. This worker can be processed multiple ways, e.g. using cron.'),
      '#disabled' => $profile->isLocked(),
      '#default_value' => $profile->hasAutomaticDownloadWorker(),
      '#states' => [
        'visible' => [
          ':input[name="auto_download"]' => ['checked' => TRUE],
        ],
      ],
    ];

    $options = [
      'global_setting' => $this->t('Use global setting'),
      'yes' => $this->t('Yes'),
      'no' => $this->t('No'),
    ];

    $form['append_type_to_title'] = [
      '#type' => 'select',
      '#title' => $this->t('Append Entity Type to Translate Document Name'),
      '#description' => $this->t('When enabled, the content/entity type will be appended to the title when uploading to  Straker Translate. The source and target titles will remain unchanged.'),
      '#options' => $options,
      '#default_value' => $profile->getAppendContentTypeToTitle(),
      '#disabled' => $profile->isLocked(),
    ];

    $form['future_only_note'] = [
      '#type' => 'markup',
      '#markup' => '<h3>' . $this->t('Profile settings impacting only new nodes') . '</h3><hr />',
    ];

    $accountConfig = $this->config('straker_translate.account');
    $workflows = $accountConfig->get('resources.workflow');
    $default_workflow = $accountConfig->get('default.workflow');

    $default_workflow_name = $workflows[$default_workflow] ?? '';

    $form['workflow'] = [
      '#type' => 'select',
      '#title' => $this->t('Workflow'),
      '#options' => [
        'default' => $this->t('Default (%workflow)', ['%workflow' => $default_workflow_name]),
      ] + $workflows,
      '#description' => $this->t('The default Workflow which would be used for translations.'),
      '#default_value' => $profile->getWorkflow(),
    ];

    $form['language_overrides'] = [
      '#type' => 'details',
      '#title' => $this->t('Target language specific settings'),
      '#tree' => TRUE,
    ];
    $languages = \Drupal::languageManager()->getLanguages();
    // Filter the disabled languages.
    $languages = array_filter($languages, function (LanguageInterface $language) {
      $configLanguage = ConfigurableLanguage::load($language->getId());
      return $this->straker_translateConfiguration->isLanguageEnabled($configLanguage);
    });

    // We want to have them alphabetically.
    ksort($languages);
    foreach ($languages as $langcode => $language) {
      $form['language_overrides'][$langcode] = [
        'overrides' => [
          '#type' => 'select',
          '#title' => $language->getName() . ' (' . $language->getId() . ')',
          '#options' => [
            'default' => $this->t('Use default settings'),
            'custom' => $this->t('Use custom settings'),
            'disabled' => $this->t('Disabled'),
          ],
          '#default_value' => $profile->getCustomSettingsForTarget($langcode),
        ],
        'custom' => [
          '#type' => 'container',
          '#attributes' => [
            'class' => 'profile-language-overrides-container',
          ],
          '#states' => [
            'visible' => [
              ':input[name="language_overrides[' . $langcode . '][overrides]"]' => ['value' => 'custom'],
            ],
          ],
          'auto_download' => [
            '#type' => 'checkbox',
            '#title' => $this->t('Download Translation Automatically'),
            '#description' => $this->t('When enabled, completed translations will automatically be downloaded from  Straker Translate. When disabled, you are required to manually download translations by clicking the "Download" button on the Translations tab.'),
            '#disabled' => $profile->isLocked(),
            '#default_value' => $profile->hasAutomaticDownloadForTarget($langcode),
          ],
        ],
      ];
    }
    $form['#attached']['library'][] = 'straker_translate/straker_translate.settings';
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    /** @var \Drupal\straker_translate\Entity\StrakerTranslateProfile $profile */
    \Drupal::service('plugin.manager.straker_translate_form_bulk_action')->clearCachedDefinitions();

    return parent::save($form, $form_state);
  }

}
