<?php

namespace Drupal\pagedesigner_yoast\Plugin\Field\FieldWidget;

use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\yoast_seo\Plugin\Field\FieldWidget\YoastSeoWidget;

/**
 * Pagedesigner widget for yoast_seo field.
 *
 * @FieldWidget(
 *   id = "pagedesigner_yoast_seo_widget",
 *   label = @Translation("Real-time SEO form for pagedesigner"),
 *   field_types = {
 *     "yoast_seo"
 *   }
 * )
 */
class PagedesignerYoastSeoWidget extends YoastSeoWidget {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    // Overwrite the body field name for yoast seo.
    $settings = [
      'body' => 'pagedesigner_yoast_content',
    ];

    return $settings + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    if ($this->getSetting('body') != 'pagedesigner_yoast_content') {
      $summary = parent::settingsSummary();
    }
    else {
      $summary = [];
      $summary[] = $this->t('Pagedesigner Content');
    }
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $element = [];
    $element['body'] = [
      '#type' => 'select',
      '#title' => $this->t('Body'),
      '#required' => TRUE,
      '#description' => $this->t('Select a field which is used as the body field.'),
      '#options' => ['pagedesigner_yoast_content' => 'Pagedesigner Content'],
      '#default_value' => 'pagedesigner_yoast_content',
    ];

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);
    if ($form_state->getFormObject() instanceof ContentEntityForm) {
      $list = [];
      $pagedesignerService = \Drupal::service('pagedesigner.service');
      $elementHandler = \Drupal::service('pagedesigner.service.element_handler');

      // Get all pagedesigner fields on the entity.
      /** @var \Drupal\node\Entity\Node $entity */
      $entity = $form_state->getFormObject()->getEntity();
      $fields = $pagedesignerService->getPagedesignerFields($entity);

      // Sort fields by default view display (text order defines status).
      $viewDisplayId = $entity->getEntityTypeId() . '.' . $entity->bundle() . '.default';
      /** @var \Drupal\Core\Entity\Entity\EntityViewDisplay $viewDisplay */
      $viewDisplay = \Drupal::entityTypeManager()->getStorage('entity_view_display')->load($viewDisplayId);
      uasort($fields, fn($a, $b) => $viewDisplay->getComponent($a->getName())['weight'] - $viewDisplay->getComponent($b->getName())['weight']);

      // Get the content of all pd fields.
      foreach ($fields as $fieldName => $field) {
        $container = $pagedesignerService->getContainer($entity, $fieldName);
        $elementHandler->getContent($container, $list, FALSE);
      }

      // Create a text field for yoast_seo to analyze.
      $form['pagedesigner_yoast'] = [
        '#type' => 'hidden',
      ];
      $form['pagedesigner_yoast_content']['widget'][0] = [
        '#type' => 'text_format',
        '#format' => 'plain_text',
        '#title' => $this->t('Pagedesigner content'),
        '#default_value' => 'this is the pd content',
        '#value' => implode("", $list),
        '#description' => $this->t("The SEO status in points."),
        '#prefix' => '<div class="hidden visually-hidden">',
        '#suffix' => '</div>',
      ];
      $element['yoast_seo']['#description'] = '<span>' . $this->t('The analysis is based on the unpublished pagedesigner content.') . '</span>';
    }
    return $element;
  }

}
