<?php

namespace Drupal\castorcito\Plugin\CastorcitoComponentField;

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

/**
 * Entity reference configuration.
 *
 * @CastorcitoComponentField(
 *   id = "block_reference",
 *   label = @Translation("Block reference"),
 *   description = @Translation("Field to reference another block.")
 * )
 */
class BlockReference extends ConfigurableComponentFieldBase {

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

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'allowed_provider' => [],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $allowed_provider = [];
    $castorcito_manager = \Drupal::service('castorcito.manager');
    $module_handler = \Drupal::service('module_handler');
    $definitions = $castorcito_manager->getBlockDefinitions();

    if (!empty($definitions)) {
      foreach ($definitions as $definition) {
        if (isset($definition['admin_label']) && $module_handler->moduleExists($definition['provider'])) {
          $allowed_provider[$definition['provider']] = $module_handler->getName($definition['provider']);
        }
      }
    }

    $form['allowed_provider'] = [
      '#type' => 'checkboxes',
      '#options' => $allowed_provider,
      '#title' => $this->t('Allowed providers'),
      '#default_value' => $this->configuration['allowed_provider'],
      '#description' => $this->t('Select the allowed block providers.'),
      '#required' => TRUE,
    ];

    return $form;
  }

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

}
