<?php

namespace Drupal\sector_toc\Plugin\EmbeddedContent;

use Drupal\embedded_content\EmbeddedContentInterface;
use Drupal\embedded_content\EmbeddedContentPluginBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
 * Plugin embedded_toc.
 *
 * @EmbeddedContent(
 *   id = "sector.embedded_toc",
 *   label = @Translation("Sector › Table of contents"),
 * )
 */
class EmbeddedTableOfContents extends EmbeddedContentPluginBase implements EmbeddedContentInterface {
  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'selectors' => 'h2',
      'heading' => '',
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function build(): array {
    $uuid = \Drupal::service('uuid')->generate();

    return [
      '#theme' => 'toc',
      '#heading' => $this->configuration['heading'],
      '#group' => $uuid,
      '#attached' => [
        'drupalSettings' => [
          'sector_toc' => [
            $uuid => [
              'selectors' => strtolower($this->configuration['selectors']) ?? NULL,
            ],
          ],
        ],
      ],
      '#cache' => [
        'tags' => [
          'sector_toc:' . $uuid,
        ],
        'contexts' => [
          'user.roles:anonymous',
        ],
      ],
    ];
  }

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

    $form['heading'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Heading'),
      '#default_value' => $this->configuration['heading'],
    ];

    $form['selectors'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Selectors'),
      '#default_value' => strtolower($this->configuration['selectors']),
      '#required' => TRUE,
      '#rows' => 10,
      '#description' => '',
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function isInline(): bool {
    return FALSE;
  }

}
