<?php

namespace Drupal\castorcito\Plugin\CastorcitoComponentField;

use Drupal\Core\Form\FormStateInterface;
use Drupal\castorcito\ConfigurableComponentFieldBase;

/**
 * Formatted text configuration.
 *
 * @CastorcitoComponentField(
 *   id = "formatted_text",
 *   label = @Translation("Formatted text"),
 *   description = @Translation("Configuration for the formatted text field.")
 * )
 */
class FormattedText extends ConfigurableComponentFieldBase {

  /**
   * {@inheritdoc}
   */
  public function defaultModel() {
    return [
      'value' => '',
      'format' => 'basic_html',
    ];
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $allowed_formats = [];
    $user = \Drupal::currentUser();
    $formats = filter_formats($user);

    if (!empty($formats)) {
      foreach ($formats as $format) {
        if ($format->id() !== 'plain_text') {
          $allowed_formats[$format->id()] = $format->label();
        }
      }
    }

    $form['allowed_formats'] = [
      '#type' => 'checkboxes',
      '#options' => $allowed_formats,
      '#title' => $this->t('Allowed text formats'),
      '#default_value' => $this->configuration['allowed_formats'],
      '#description' => $this->t('Select the allowed text formats. If no formats are selected, all available text formats will be displayed to the user.'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration['allowed_formats'] = array_filter($form_state->getValue('allowed_formats'));
  }

  /**
   * {@inheritdoc}
   */
  public function overridableConfiguration() {
    return parent::overridableConfiguration() + [
      'allowed_formats',
    ];
  }

}
