<?php

namespace Drupal\straker_translate\Plugin\StrakerTranslateFormComponent\Field;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Link;
use Drupal\straker_translate\FormComponent\StrakerTranslateFormComponentBundleTrait;
use Drupal\straker_translate\FormComponent\StrakerTranslateFormComponentFieldBase;

/**
 * Defines a Straker Translate form-field plugin for an entity's label.
 *
 * @StrakerTranslateFormComponentField(
 *   id = "title",
 *   title = @Translation("Title"),
 *   weight = 200,
 *   form_ids = {
 *     "straker_translate_management",
 *     "straker_translate_entity_management",
 *     "straker_translate_job_content_entities_management"
 *   }
 * )
 */
class Title extends StrakerTranslateFormComponentFieldBase {

  use StrakerTranslateFormComponentBundleTrait;

  /**
   * {@inheritdoc}
   */
  public function getHeader($entity_type_id = NULL) {
    if ($entity_type_id === NULL) {
      return $this->t('Label');
    }
    $entity_type = $this->getEntityType($entity_type_id);
    /** @var \Drupal\Core\Entity\EntityFieldManagerInterface $field_manager */
    $field_manager = \Drupal::service('entity_field.manager');
    $properties = $field_manager->getBaseFieldDefinitions($entity_type_id);
    $header = $this->hasBundles($entity_type_id) && $entity_type->hasKey('label') ? $properties[$entity_type->getKey('label')]->getLabel() : $entity_type->getLabel();

    return ['data' => $header];
  }

  /**
   * {@inheritdoc}
   */
  public function getData(EntityInterface $entity) {
    return $entity->hasLinkTemplate('canonical') ? Link::fromTextAndUrl($entity->label(), $entity->toUrl()) : $entity->label();
  }

}
