<?php

namespace Drupal\nodehive_core\Plugin\Field\FieldFormatter;

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

/**
 * Plugin implementation of the 'nodehive_variant_selector_formatter' formatter.
 *
 * @FieldFormatter(
 *   id = "nodehive_variant_selector_formatter",
 *   label = @Translation("Variant Selector Display"),
 *   field_types = {
 *     "nodehive_variant_selector"
 *   }
 * )
 */
class NodeHiveVariantSelectorFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];

    // Fetch the field settings.
    $field_settings = $this->getFieldSetting('variants');

    foreach ($items as $delta => $item) {
      $key = $item->key;

      // Search for the title associated with the key.
      $title = '';
      foreach ($field_settings as $variant) {
        if ($variant['key'] === $key) {
          $title = $variant['title'];
          break;
        }
      }

      $markup = "{$title} <small>({$key})</small>";
      $elements[$delta] = ['#markup' => $markup];
    }

    return $elements;
  }

}
