<?php

namespace Drupal\author_field\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;

/**
 * Plugin implementation of the 'Default' formatter.
 *
 * @FieldFormatter(
 *   id = "author_field_default",
 *   module = "author_field",
 *   label = @Translation("Default"),
 *   field_types = {
 *     "author_field"
 *   }
 * )
 */
class AuthorFieldDefaultFormatter extends FormatterBase {

  /**
   * Plugin implementation of the 'Default' formatter.
   *
   * The default formatter configures simply the author name link,
   * email, and ORCID ID of the author.
   */
  public function viewElements(FieldItemListInterface $items, $langcode): array {
    $element = [];

    $total_count = count($items);
    $authors = [];
    $organization_list = [];
    foreach ($items as $delta => $item) {
      $author = [];
      $values = $item->getValue();

      if (!empty($values['organization_name'])) {
        $index = array_search($values['organization_name'], $organization_list);
        if ($index === FALSE) {
          $organization_list[] = $values['organization_name'];
          $index = count($organization_list);
        }
        else {
          $index += 1;
        }
        $author['superscript'] = $index;
      }
      else {
        $author['superscript'] = NULL;
      }

      $author['given_name'] = $values['given_name'];
      $author['family_name'] = $values['family_name'];
      $author['email'] = $values['email'];
      $author['orcid_id'] = $values['orcid_id'];
      $author['organization_name'] = $values['organization_name'];
      $author['delta'] = $total_count;
      $authors[] = $author;
    }

    if (!empty($authors)) {
      $element[0] = [
        '#theme' => 'author_field_default',
        '#attributes' => [
          'class' => [
            'author_field',
          ],
        ],
      ];

      $element[0]['#authors'] = $authors;
      $element[0]['#organization_list'] = $organization_list;
    }

    return $element;
  }

}
