<?php

namespace Drupal\languagewire_translation_provider\Adapter\TMGMT;

use Drupal\languagewire_translation_provider\Content\TMGMTContent;
use Drupal\tmgmt\JobItemInterface;
use function array_keys;
use function array_walk;

/**
 * TMGMT Job Item Adapter.
 * */
class TmgmtJobItem implements TmgmtJobItemInterface {
  /**
   * Job item.
   *
   * @var \Drupal\tmgmt\JobItemInterface
   */
  private JobItemInterface $jobItem;

  /**
   * Constructs a new TmgmtJobItem object.
   *
   * @param \Drupal\tmgmt\JobItemInterface $jobItem
   *   Job item.
   */
  public function __construct(JobItemInterface $jobItem) {
    $this->jobItem = $jobItem;
  }

  /**
   * Label.
   */
  public function label(): string {
    return $this->jobItem->label();
  }

  /**
   * Item ID.
   */
  public function itemId(): int {
    return $this->jobItem->id();
  }

  /**
   * Add message.
   */
  public function addMessage(string $message): void {
    $this->jobItem->addMessage($message);
  }

  /**
   * Add error.
   */
  public function addError(string $message): void {
    $this->jobItem->addMessage($message, [], 'error');
  }

  /**
   * Set as active.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function setAsActive(): void {
    $this->jobItem->active();
    $this->activateTranslatableContent();
  }

  /**
   * Get content.
   *
   * @return \Drupal\languagewire_translation_provider\Content\TMGMTContent[]
   *   The contents.
   */
  public function getContent(): array {
    $content = [];
    $itemContent = $this->getTranslatableContent([$this->itemId() => $this->getRawData()]);

    foreach ($itemContent as $contentId => $flattenedContent) {
      $content[] = new TMGMTContent($contentId, $flattenedContent);
    }

    return $content;
  }

  /**
   * Get raw data.
   */
  public function getRawData(): array {
    return $this->jobItem->getData();
  }

  /**
   * Get wrapped objects entity type.
   */
  public function getWrappedObjectsEntityType(): string {
    return $this->jobItem->getItemType();
  }

  /**
   * Get wrapped objects entity id.
   */
  public function getWrappedObjectsEntityId(): string {
    return $this->jobItem->getItemId();
  }

  /**
   * Activate translatable content.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  private function activateTranslatableContent(): void {
    $contentIds = array_keys($this->getTranslatableContent($this->getRawData()));

    array_walk($contentIds, function (string $contentId): void {
        $this->jobItem->updateData($contentId, ['#status' => TMGMT_DATA_ITEM_STATE_PENDING]);
    });

    $this->jobItem->save();
  }

  /**
   * Get translatable content.
   */
  private function getTranslatableContent(array $itemContent): array {
    $tmgmtDataService = \Drupal::service('tmgmt.data');

    return $tmgmtDataService->filterTranslatable($itemContent);
  }

}
