<?php

namespace Drupal\node_view_mode\Plugin\Field\FieldWidget;

use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\StringTextfieldWidget;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
use Drupal\node\Entity\NodeType;
use Drupal\node_view_mode\Enum\ViewModes;
use Drupal\node_view_mode\Enum\WidgetSettings;
use Drupal\node_view_mode\StorageManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Plugin implementation of the 'node_view_mode' widget.
 *
 * @FieldWidget(
 *   id = "node_view_mode",
 *   label = @Translation("Node view mode"),
 *   field_types = {
 *     "node_view_mode",
 *   }
 * )
 */
class NodeViewModeWidget extends StringTextfieldWidget {

  /**
   * Current request.
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;

  /**
   * Entity form builder.
   *
   * @var \Drupal\Core\Entity\EntityFormBuilderInterface
   */
  protected $entityFormBuilder;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->request = $container->get('request_stack')->getCurrentRequest();
    $instance->entityFormBuilder = $container->get('entity.form_builder');

    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      WidgetSettings::ViewModes->value => self::getAvailableViewModes(),
      WidgetSettings::DefaultViewMode->value => ViewModes::Default->value,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {

    $element[WidgetSettings::ViewModes->value] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Available view modes'),
      '#description' => $this->getViewModesFieldDescription(),
      '#options' => $this->defaultSettings()[WidgetSettings::ViewModes->value],
      '#default_value' => array_keys($this->getEnabledViewModes()),
      '#required' => FALSE,
      '#ajax' => [
        'callback' => [__CLASS__, 'defaultViewModes'],
        'event' => 'change',
        'wrapper' => 'node-view-mode-default',
      ],
    ];

    if ($this->getSetting(WidgetSettings::ViewModes->value)) {
      $element[WidgetSettings::DefaultViewMode->value] = [
        '#type' => 'select',
        '#title' => $this->t('Default value'),
        '#description' => $this->t('View mode to be used as a default field value.'),
        '#options' => $element[WidgetSettings::ViewModes->value]['#options'],
        '#default_value' => $this->getSetting(WidgetSettings::DefaultViewMode->value),
        '#required' => FALSE,
        '#weight' => 2,
        '#prefix' => '<div id="node-view-mode-default">',
        '#suffix' => '</div>',
      ];
    }

    return $element;
  }

  /**
   * Ajax callback for updating the default view mode options.
   *
   * @param array $form
   *   Form structure.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state.
   *
   * @return array
   *   Default view mode form element.
   */
  public static function defaultViewModes(array $form, FormStateInterface $form_state) {
    $checkboxes = $form_state->getTriggeringElement();
    $element = NestedArray::getValue($form, array_slice($checkboxes['#array_parents'], 0, count($checkboxes['#array_parents']) - 2));

    $options = array_intersect_key($element[WidgetSettings::ViewModes->value]['#options'], $element[WidgetSettings::ViewModes->value]['#value']);

    $element[WidgetSettings::DefaultViewMode->value]['#options'] = empty($options) ? $element[WidgetSettings::ViewModes->value]['#options'] : $options;

    return $element[WidgetSettings::DefaultViewMode->value];
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $settings = $this->getEnabledViewModes();

    if (empty($settings)) {
      $message = $this->t('No view modes enabled, "@default" view mode will be used instead.', [
        '@default' => ViewModes::Default->value,
      ]);
    }
    else {
      $message = $this->t('Available view modes: @types', ['@types' => implode(', ', $settings)]);
    }

    $summary[] = $message;

    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    $wrapper_id = 'view-mode-node-' . $items->getEntity()->uuid();

    $element['value'] = [
      '#title' => $items->getFieldDefinition()->getLabel(),
      '#type' => 'select',
      '#default_value' => $items[$delta]->value ?? $this->getSetting(WidgetSettings::DefaultViewMode->value),
      '#options' => $this->getEnabledViewModes() ?: $this->getDefaultOption(),
      '#required' => TRUE,
      '#weight' => 1,
    ] + $element['value'];

    return $element;
  }

  /**
   * Getter for available view modes in node entity type.
   *
   * @return array
   *   Associative array of view mode machine names and labels.
   */
  protected static function getAvailableViewModes(): array {
    $request = \Drupal::request();
    /** @var \Drupal\Core\Entity\EntityDisplayRepository $entity_display_repository */
    $entity_display_repository = \Drupal::service('entity_display.repository');
    $node_type = self::getNodeTypeFromRequest($request);

    $entity_id = StorageManagerInterface::ENTITY_TYPE;

    if ($node_type instanceof NodeType) {
      $viewModes = $entity_display_repository->getViewModeOptionsByBundle($entity_id, $node_type->id());
    }
    else {
      $viewModes = $entity_display_repository->getViewModeOptions($entity_id);
    }

    asort($viewModes);
    return $viewModes;
  }

  /**
   * Getter for enabled view modes.
   *
   * @return array
   *   Associative array of view mode machine names and labels.
   */
  protected function getEnabledViewModes(): array {
    $availableViewModes = self::getAvailableViewModes();
    $currentViewModes = array_filter($this->getSetting(WidgetSettings::ViewModes->value));

    return array_intersect_key($availableViewModes, $currentViewModes);
  }

  /**
   * Provides default option for the form elements.
   *
   * @return array
   *   Default view mode option.
   */
  protected function getDefaultOption() {
    return [ViewModes::Default->value => $this->t('Default')];
  }

  /**
   * Get NodeType entity object from request.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   Current request object.
   *
   * @return \Drupal\node\Entity\NodeType|null
   *   NodeType entity.
   */
  protected static function getNodeTypeFromRequest(Request $request): ?NodeType {
    return $request->attributes->get('node_type', NULL);
  }

  /**
   * Getter for 'view modes' field description.
   *
   * @return null|\Drupal\Core\StringTranslation\TranslatableMarkup
   *   return null|Field description.
   */
  protected function getViewModesFieldDescription(): ?TranslatableMarkup {
    $node_type = self::getNodeTypeFromRequest($this->request);
    if (empty($node_type)) {
      return NULL;
    }

    $url_route = implode('.', [
      'entity.entity_view_display',
      StorageManagerInterface::ENTITY_TYPE,
      ViewModes::Default->value,
    ]);
    $url_parameters = ['node_type' => $node_type->id()];
    $url_options = ['fragment' => 'edit-modes'];

    $url = Url::fromRoute($url_route, $url_parameters, $url_options);

    return $this->t('It is using only the view modes enabled in the <strong>CUSTOM DISPLAY SETTINGS</strong> section under the <a href="@url">Manage Display</a> tab.', ['@url' => $url->toString()]);
  }

}
