<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\Platform\Document;

use Drupal\languagewire_translation_provider\api\Libraries\Content\Udf\Frame as PlatformFrame;
use Drupal\languagewire_translation_provider\api\Libraries\Document\PlatformDocument;
use Drupal\languagewire_translation_provider\Content\SanitizerInterface;
use Drupal\languagewire_translation_provider\Content\TranslatedContent;
use Drupal\languagewire_translation_provider\Domain\Document;
use Drupal\languagewire_translation_provider\Domain\DocumentStatus;

/**
 * Translated Document.
 */
final class TranslatedDocument extends DocumentBase {

  /**
   * Contents.
   *
   * @var \Drupal\languagewire_translation_provider\Content\TranslatedContent[]
   */
  private array $contents;

  /**
   * Constructs a new TranslatedDocument object.
   *
   * @param \Drupal\languagewire_translation_provider\Content\TranslatedContent[] $contents
   *   Contents.
   * @param \Drupal\languagewire_translation_provider\Domain\Document|null $document
   *   Document.
   */
  public function __construct(array $contents, ?Document $document) {
    parent::__construct($document);
    $this->contents = $contents;
  }

  /**
   * From Platform Document.
   */
  public static function fromPlatformDocument(PlatformDocument $platformDocument, ?Document $document): self {
    $content = array_map(function (PlatformFrame $platformFrame): TranslatedContent {
        return TranslatedContent::fromPlatformFrame($platformFrame);
    }, $platformDocument->getContent()->getUdf()->getFrames());

    return new self($content, $document);
  }

  /**
   * Get Content.
   *
   * @return \Drupal\languagewire_translation_provider\Content\TranslatedContent[]
   *   Contents.
   */
  public function translatedContent(): array {
    return $this->contents;
  }

  /**
   * Desanitize Content.
   */
  public function desanitizeContent(SanitizerInterface $sanitizer): void {
    $this->contents = array_map(function (TranslatedContent $content) use ($sanitizer) {
        return $content->desanitize($sanitizer);
    }, $this->contents);
  }

  /**
   * To TMGMT Import Data.
   */
  public function toTmgmtImportData(): array {
    $data = [];

    foreach ($this->contents as $content) {
      $data[$content->contentId()] = [
        '#text' => $content->translatedContent(),
        '#origin' => 'remote',
      ];
    }

    return $data;
  }

  /**
   * Update Domain Document.
   */
  public function updateDomainDocument(): void {
    $this->document->setStatus(DocumentStatus::translated());
  }

}
