<?php

namespace Drupal\straker_translate\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\LanguageFormatter;
use Drupal\Core\Form\FormStateInterface;
use Drupal\straker_translate\Entity\StrakerTranslateContentMetadata;
use Drupal\straker_translate\StrakerTranslate;

/**
 * Plugin implementation of the 'straker_translate_translation_status' formatter.
 *
 * @FieldFormatter(
 *   id = "straker_translate_source_status",
 *   label = @Translation("Straker Translate source status"),
 *   field_types = {
 *     "language",
 *   }
 * )
 */
class StrakerTranslateSourceStatusFormatter extends LanguageFormatter {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    $settings = [];
    return $settings;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form = [];
    return $form;
  }

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

  /**
   * {@inheritdoc}
   *
   * @throws \Drupal\Core\TypedData\Exception\MissingDataException
   */
  protected function viewValue(FieldItemInterface $item) {
    $entity = $item->getEntity();
    $source_status = StrakerTranslate::STATUS_UNTRACKED;
    if ($entity instanceof StrakerTranslateContentMetadata) {
      // $entity is the metadata of another entity. Let's get the source.
      // @todo Use injected service. See https://www.drupal.org/project/drupal/issues/2981025#comment-12707077.
      $entity = \Drupal::entityTypeManager()->getStorage($entity->getContentEntityTypeId())->load($entity->getContentEntityId());
      $source_status = \Drupal::service('straker_translate.content_translation')->getSourceStatus($entity);
    }

    $data = [
      'data' => [
        '#type' => 'straker_translate_source_status',
        '#entity' => $entity,
        '#language' => $item->language,
        '#status' => $source_status,
      ],
      '#attached' => [
        'library' => [
          'straker_translate/straker_translate',
        ],
      ],
      '#cache' => [
        'max-age' => 0,
      ],
    ];
    if ($source_status == StrakerTranslate::STATUS_EDITED && !\Drupal::service('straker_translate.content_translation')->getDocumentId($entity)) {
      $data['data']['#context']['status'] = strtolower(StrakerTranslate::STATUS_REQUEST);
    }
    return $data;

  }

  /**
   *
   */
  protected function getDestinationWithQueryArray() {
    return ['destination' => \Drupal::request()->getRequestUri()];
  }

}
