<?php

namespace Drupal\vue_link_formatter\Plugin\Field\FieldFormatter;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\StringFormatter;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Plugin implementation of the 'string' formatter + @click vue attribute
 *
 * @FieldFormatter(
 *   id = "vuestring",
 *   label = @Translation("Vue link Plain text"),
 *   field_types = {
 *     "string",
 *     "uri",
 *   },
 *   quickedit = {
 *     "editor" = "plain_text"
 *   }
 * )
 */
class VueStringFormatter extends StringFormatter {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    $url = NULL;
    if ($this->getSetting('link_to_entity')) {
      $entity = $items->getEntity();
      $url = $this->getEntityUrl($entity);
    }

    foreach ($items as $delta => $item) {
      $view_value = $this->viewValue($item);
      if ($url) {
        $elements[$delta] = [
          '#type' => 'link',
          '#title' => $view_value,
          '#url' => $url,
          '#attributes' => array(
            '@click.prevent' => 'onClickLink',
            'data-id' => $entity->id(),
            'data-entity-type' => $entity->getEntityTypeId(),
            'data-bundle' => $entity->bundle(),
            // 'data-bundle' => $entity
            // 'nid' => $entity->nid(),
            // 'type' => $entity->getType()
          )
        ];
      }
      else {
        $elements[$delta] = $view_value;
      }
    }
    return $elements;
  }

}
