<?php

namespace Drupal\straker_translate\Plugin\Field;

use Drupal\Core\Field\EntityReferenceFieldItemList;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\TypedData\TypedDataInterface;
use Drupal\straker_translate\Entity\StrakerTranslateContentMetadata;

/**
 * A computed field that provides a content entity's Straker Translate metadata.
 */
class StrakerTranslateContentMetadataFieldItemList extends EntityReferenceFieldItemList {

  /**
   * Gets the Straker Translate metadata entity linked to a content entity revision.
   *
   * @return \Drupal\straker_translate\Entity\StrakerTranslateContentMetadata|null
   *   The content entity's Straker Translate metadata.
   */
  protected function getContentMetadata(): ?StrakerTranslateContentMetadata {
    $entity = $this->getEntity();

    /** @var \Drupal\straker_translate\StrakerTranslateConfigurationService $config_service */
    $config_service = \Drupal::service('straker_translate.configuration');
    if (!$config_service->isEnabled($entity->getEntityTypeId(), $entity->bundle())) {
      return NULL;
    }

    if ($entity->id()) {
      $metadata_result = \Drupal::entityTypeManager()->getStorage('straker_content_metadata')->getQuery()
        ->accessCheck(FALSE)
        ->condition('content_entity_type_id', $entity->getEntityTypeId())
        ->condition('content_entity_id', $entity->id())
        ->execute();

      if ($metadata_id = key($metadata_result)) {
        /** @var \Drupal\straker_translate\Entity\StrakerTranslateContentMetadata $metadata */
        $metadata = \Drupal::entityTypeManager()
          ->getStorage('straker_content_metadata')
          ->load($metadata_id);

        return $metadata;
      }
    }
    $metadata = StrakerTranslateContentMetadata::create();
    if ($entity->id()) {
      $metadata->setEntity($entity);
      $metadata->save();
    }
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function get($index): TypedDataInterface|FieldItemInterface|null {
    if ($index !== 0) {
      throw new \InvalidArgumentException('An entity can not have multiple moderation states at the same time.');
    }
    if (isset($this->list[$index]) && !$this->list[$index]->isEmpty()) {
      return $this->list[$index];
    }
    $this->computeStrakerTranslateMetadataFieldItemList();
    return $this->list[$index] ?? NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function getIterator(): \ArrayIterator {
    $this->computeStrakerTranslateMetadataFieldItemList();
    return parent::getIterator();
  }

  /**
   * Recalculate the Straker Translate metadata field item list.
   */
  protected function computeStrakerTranslateMetadataFieldItemList() {
    // Compute the value of the moderation state.
    $index = 0;
    if (!isset($this->list[$index]) || $this->list[$index]->isEmpty()) {
      $metadata = $this->getContentMetadata();
      // Do not store NULL values in the static cache.
      if ($metadata) {
        $this->list[$index] = $this->createItem($index, ['entity' => $metadata]);
      }
    }
  }

  /**
   * {@inheritDoc}
   */
  public function preSave() {
    /** @var \Drupal\straker_translate\Entity\StrakerTranslateContentMetadata $metadata */
    $metadata = $this->getContentMetadata();
    if ($metadata && !$metadata->getContentEntityId()) {
      $metadata->setEntity($this->getEntity());
    }
    parent::preSave();
  }

}
