<?php

namespace Drupal\pagedesigner\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\pagedesigner\Plugin\DataType\PagedesignerData;

/**
 * Plugin implementation of the Pagedesigner content field type.
 *
 * @FieldType(
 *   id = "pagedesigner_item",
 *   label = @Translation("Pagedesigner content"),
 *   module = "pagedesigner",
 *   description = @Translation("Defines a pagedesigner field."),
 *   default_widget = "pagedesigner_entity_reference_autocomplete",
 *   default_formatter = "pagedesigner_formatter",
 *   translatable = true,
 *   list_class = "\Drupal\Core\Field\EntityReferenceFieldItemList",
 * )
 */
class PagedesignerItem extends EntityReferenceItem {

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);
    $properties['content'] = DataDefinition::create('pagedesigner_item_data')
      ->setLabel(new TranslatableMarkup('Pagedesigner content'))
      ->setComputed(TRUE)
      ->setClass(PagedesignerData::class)
      ->setInternal(FALSE);
    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
    $element = [];
    $element['target_type'] = [
      '#type' => 'select',
      '#title' => $this->t('Type of item to reference'),
      '#options' => ['pagedesigner_element' => 'Pagedesigner element'],
      '#default_value' => 'pagedesigner_element',
      '#required' => TRUE,
      '#disabled' => TRUE,
      '#size' => 1,
    ];
    return $element;

  }

  /**
   * {@inheritdoc}
   */
  public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
    $form = parent::fieldSettingsForm($form, $form_state);
    $form['handler']['handler']['#options'] = ['default:pagedesigner_element' => $form['handler']['handler']['#options']['default:pagedesigner_element']];
    $form['handler']['handler_settings']['auto_create']['#type'] = 'hidden';
    $form['handler']['handler_settings']['target_bundles']['#default_value'] = ['container'];
    $form['handler']['handler_settings']['target_bundles']['#options'] = ['container' => $form['handler']['handler_settings']['target_bundles']['#options']['container']];
    return $form;

  }

}
