<?php

namespace Drupal\rocketship_office_core\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;

/**
 * Plugin implementation of the 'contact_us_button' formatter.
 *
 * @FieldFormatter(
 *   id = "contact_us_button",
 *   label = @Translation("Contact Us button"),
 *   field_types = {
 *     "boolean"
 *   }
 * )
 */
class ContactUsButton extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    // TODO: Change the autogenerated stub.
    return ['link_text' => 'Contact us'] + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $elements = parent::settingsForm($form, $form_state);

    $elements['link_text'] = [
      '#title' => $this->t('Link text'),
      '#type' => 'textfield',
      '#required' => TRUE,
      '#description' => $this->t('The text to show in the link'),
      '#default_value' => $this->getSetting('link_text'),
    ];

    return $elements;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = [];

    $summary[] = $this->t('Output the "Contact us" scroll-to button when the field value evaluates to true');
    $summary[] = $this->t('Link text: @text', ['@text' => $this->getSetting('link_text')]);

    // Implement settings summary.
    return $summary;
  }

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

    foreach ($items as $delta => $item) {
      if ($item->value == TRUE) {
        /** @var \Drupal\node\NodeInterface $entity */
        $entity = $items->getEntity();
        $entity = $entity->getTranslation($langcode);
        $url = $entity->toUrl('canonical', ['fragment' => rocketship_OFFICE_CORE_ANCHOR]);
        $link_text = $this->getSetting('link_text');
        $elements[$delta] = Link::fromTextAndUrl($this->t($link_text), $url)
          ->toRenderable();
      }
    }

    return $elements;
  }

}
