<?php

namespace Drupal\straker_translate\Plugin\Field\FieldType;

use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Core\Field\FieldItemList;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\TypedData\ComputedItemListTrait;

/**
 *
 */
class StrakerTranslateTranslationSourceField extends FieldItemList implements FieldItemListInterface {

  use ComputedItemListTrait;

  /**
   * Compute the values.
   */
  protected function computeValue() {
    /** @var \Drupal\straker_translate\Entity\StrakerTranslateContentMetadata $metadata */
    $metadata = $this->getEntity();
    $entity_type_id = $metadata->getContentEntityTypeId();
    $entity_id = $metadata->getContentEntityId();
    if ($entity_type_id && $entity_id) {
      try {
        $target_entity = \Drupal::entityTypeManager()
          ->getStorage($entity_type_id)
          ->load($entity_id);
        if ($target_entity) {
          $this->list[0] = $this->createItem(0,
            $target_entity->language()->getId());
        }
      }
      catch (InvalidPluginDefinitionException | PluginNotFoundException $e) {
      }
    }
  }

}
