<?php

namespace Drupal\sector_toc\Plugin\Block;


use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Cache\Cache;

/**
 * Provides an example block.
 *
 * @Block(
 *   id = "sector_toc",
 *   admin_label = @Translation("Sector › Table of contents"),
 *   category = @Translation("Sector")
 * )
 */
class TableOfContents extends BlockBase {

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

  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      '#theme' => 'toc',
      '#heading' => $this->configuration['heading'],
      '#selectors' => $this->configuration['selectors'],
      '#cache' => [
        'tags' => [
          'sector_toc',
        ],
        'contexts' => [
          'user.roles:anonymous'
        ]
      ]
    ];
  }


  /**
   * {@inheritdoc}
   */
  public function blockForm($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' => $this->configuration['selectors'],
      '#required' => TRUE,
      '#rows' => 10,
      '#description' => ''
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['selectors'] = $form_state->getValue('selectors');
    $this->configuration['heading'] = $form_state->getValue('heading');
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags(): array {
    return Cache::mergeTags(parent::getCacheTags(), ['sector_toc']);
  }
}
