<?php

namespace Drupal\author_field\Plugin\Field\FieldType;

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

/**
 * Plugin implementation of the 'author_field' field type.
 *
 * Provides a field type of the author.
 *
 * @FieldType(
 *   id = "author_field",
 *   module = "author_field",
 *   label = @Translation("Author Field"),
 *   category = @Translation("General"),
 *   default_widget = "author_field_widget",
 *   default_formatter = "author_field_default"
 * )
 */
class AuthorFieldItem extends FieldItemBase {

  /**
   * The method determines when the field is empty.
   *
   * @throws \Drupal\Core\TypedData\Exception\MissingDataException
   */
  public function isEmpty(): bool {
    $value = $this->get('family_name')->getValue();

    return $value === NULL || $value === '';
  }

  /**
   * The method defines more details about properties of the author field.
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition): array {

    $properties['family_name'] = DataDefinition::create('string')
      ->setLabel(t('Family name'));
    $properties['given_name'] = DataDefinition::create('string')
      ->setLabel(t('Given name'));
    $properties['email'] = DataDefinition::create('string')
      ->setLabel(t('Email'));
    $properties['orcid_id'] = DataDefinition::create('string')
      ->setLabel(t('ORCID ID'));
    $properties['organization_name'] = DataDefinition::create('string')
      ->setLabel(t('Organization name'));

    return $properties;
  }

  /**
   * Stores the values for the author fields into the database.
   *
   * @return array[]
   *   Returns an array of schema API columns.
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition): array {

    $columns = [
      'family_name' => [
        'type' => 'varchar',
        'length' => 255,
      ],
      'given_name' => [
        'type' => 'varchar',
        'length' => 255,
      ],
      'email' => [
        'type' => 'varchar',
        'length' => 255,
      ],
      'orcid_id' => [
        'type' => 'varchar',
        'length' => 255,
      ],
      'organization_name' => [
        'type' => 'varchar',
        'length' => 255,
      ],
    ];

    return [
      'columns' => $columns,
    ];
  }

}
