<?php

namespace Drupal\nodehive_core\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\TypedData\DataDefinition;

/**
 * Plugin implementation of the 'variant_selector' field type.
 *
 * @FieldType(
 *   id = "nodehive_variant_selector",
 *   label = @Translation("NodeHive Variant Selector"),
 *   description = @Translation("Define grouped variants."),
 *   default_widget = "nodehive_variant_selector_widget",
 *   default_formatter = "nodehive_variant_selector_formatter",
 *   category = @Translation("NodeHive"),
 * )
 */
class NodeHiveVariantSelectorItem extends FieldItemBase {

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return [
      'columns' => [
        'key' => [
          'type' => 'varchar',
          'length' => 255,
        ],
      ],
      'indexes' => [
        'key' => ['key'],
      ],
    ];
  }

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

  /**
   * {@inheritdoc}
   */
  public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
    $element = [];

    $structured_variants = $this->getSetting('variants');
    if (!is_array($structured_variants)) {
      $structured_variants = [];
    }

    $element['variants'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Variants'),
      '#description' => $this->t(
        'Enter one variant per line, in the format: category|key|Variant Title'
      ),
      '#default_value' => implode("\n", array_map(function ($item) {
          return "{$item['category']}|{$item['key']}|{$item['title']}";
      }, $structured_variants)),
      '#element_validate' => [[get_class($this), 'validateVariants']],
    ];

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public static function validateVariants($element, FormStateInterface $form_state) {
    $variants_value = $element['#value'];
    $variants = array_filter(explode("\n", $variants_value));
    $structured_variants = [];

    foreach ($variants as $variant) {
      [$category, $key, $title] = explode('|', $variant);
      $structured_variants[] = [
        'category' => $category,
        'key' => $key,
        'title' => $title,
      ];
    }

    $form_state->setValueForElement($element, $structured_variants);
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['key'] = DataDefinition::create('string')
      ->setLabel(t('Key'));

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    $value = $this->get('key')->getValue();
    return $value === NULL || $value === '';
  }

}
