<?php

namespace Drupal\acquia_contenthub_publisher\Form;

use Drupal\acquia_contenthub_publisher\Libs\ExcludeSettingsInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Implements a form to exclude fields.
 */
class AcquiaContentHubExcludeFieldsForm extends ConfigFormBase {

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

  /**
   * The bundle name.
   *
   * @var string
   */
  protected string $bundle = '';

  /**
   * Array of the fields that should not be listed.
   *
   * @var array
   * @see AcquiaContentHubEvents::EXCLUDE_CONTENT_ENTITY_FIELD
   */
  protected const FIELDS_TO_BE_REMOVED = [
    'entity_subqueue' => 'id',
    'paragraph' => 'parent_id',
    'path_alias' => 'path',
  ];

  /**
   * The entity field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected EntityFieldManagerInterface $entityFieldManager;

  /**
   * Field Exclude Setting.
   *
   * @var \Drupal\acquia_contenthub_publisher\Libs\ExcludeSettingsInterface
   */
  protected ExcludeSettingsInterface $excludeSettings;

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

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return ['acquia_contenthub_publisher.exclude_settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function __construct(ConfigFactoryInterface $config, TypedConfigManagerInterface $typedConfigManager, RouteMatchInterface $route_match, EntityFieldManagerInterface $entity_field_manager, ExcludeSettingsInterface $exclude_settings) {
    if (version_compare(\Drupal::VERSION, '10.2.0', '>=')) {
      parent::__construct($config, $typedConfigManager);
    }
    else {
      parent::__construct($config);
    }
    $this->entityTypeId = $route_match->getParameter('entity_type_id');
    $this->bundle = $route_match->getParameter('bundle');
    $this->entityFieldManager = $entity_field_manager;
    $this->excludeSettings = $exclude_settings;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('config.typed'),
      $container->get('current_route_match'),
      $container->get('entity_field.manager'),
      $container->get('acquia_contenthub_publisher.exclude.settings'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state): array {
    $form['export_table'] = [
      '#type' => 'table',
      '#header' => [
        'field' => $this->t('Fields'),
        'exclude_from_export' => $this->t('Exclude from export'),
      ],
    ];

    $excluded_fields = $this->excludeSettings->getExcludedFields($this->entityTypeId, $this->bundle);
    $field_manager = $this->entityFieldManager->getFieldDefinitions($this->entityTypeId, $this->bundle);
    foreach ($field_manager as $field_name => $field_definition) {
      if (!$this->shouldBeDisplayed($field_name)) {
        continue;
      }
      $form['export_table'][$field_name]['field'] = ['#markup' => $field_name];
      if ($this->shouldBeDisabled($field_definition->isRequired(), $field_name)) {
        $form['export_table'][$field_name]['exclude_from_export'] = [
          '#type' => 'checkbox',
          '#default_value' => in_array($field_name, $excluded_fields),
          '#disabled' => TRUE,
          '#attributes' => [
            'title' => $this->t('Required fields cannot be excluded.'),
          ],
        ];
      }
      else {
        $form['export_table'][$field_name]['exclude_from_export'] = [
          '#type' => 'checkbox',
          '#default_value' => in_array($field_name, $excluded_fields),
        ];
      }
    }

    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#id' => 'exclude-fields-save',
      '#button_type' => 'primary',
      '#submit' => [[$this, 'updateExcludeSettings']],
    ];

    return $form;
  }

  /**
   * Updates exclude settings.
   *
   * @param array $form
   *   The current form.
   * @param \Drupal\Core\Form\FormStateInterface $formState
   *   The state of the current form.
   */
  public function updateExcludeSettings(array &$form, FormStateInterface $formState): void {
    $export_table_values = $formState->getValue('export_table');
    $new_excluded_fields = array_keys(array_filter($export_table_values, function ($value) {
      return isset($value['exclude_from_export']) && $value['exclude_from_export'] == 1;
    }));
    $this->excludeSettings->excludeFields($this->entityTypeId, $this->bundle, $new_excluded_fields);
    $this->excludeSettings->save();
    $this->messenger()->addMessage($this->t('Your exclude settings have been saved.'));
  }

  /**
   * Checks if the provided field should be displayed as disabled.
   *
   * @param bool $required
   *   Field isRequired value.
   * @param string $field_name
   *   Name of the field.
   *
   * @return bool
   *   Returns true if field should be disabled otherwise false.
   */
  protected function shouldBeDisabled(bool $required, string $field_name): bool {
    return $required || $field_name === 'uuid';
  }

  /**
   * Checks if the provided field should be displayed or not.
   *
   * @param string $field_name
   *   Name of the field.
   *
   * @return bool
   *   Returns true if field should be displayed otherwise false.
   */
  protected function shouldBeDisplayed(string $field_name): bool {
    if ($field_name === 'revision' || $field_name === 'langcode') {
      return FALSE;
    }
    foreach (self::FIELDS_TO_BE_REMOVED as $key => $value) {
      if ($this->entityTypeId === $key && $field_name === $value) {
        return FALSE;
      }
    }
    return TRUE;
  }

}
