<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\api\Libraries\Content;

use Drupal\languagewire_translation_provider\api\Libraries\Content\Serialize\DocumentJsonSerializer;
use Drupal\languagewire_translation_provider\api\Libraries\Content\Udf\UniversalDocumentInterface;
use Laminas\Diactoros\Stream;
use Psr\Http\Message\StreamInterface;

/**
 * Universal Document Format Content.
 */
final class UdfContent implements ContentInterface {
  /**
   * Udf .
   *
   * @var \Drupal\languagewire_translation_provider\api\Libraries\Content\Udf\UniversalDocumentInterface
   */
  private UniversalDocumentInterface $udf;
  /**
   * Serializer .
   *
   * @var \Drupal\languagewire_translation_provider\api\Libraries\Content\Serialize\DocumentJsonSerializer
   */
  private DocumentJsonSerializer $serializer;
  /**
   * Stream .
   *
   * @var \Drupal\languagewire_translation_provider\api\Libraries\Content\ContentInterface
   */
  private ContentInterface $stream;

  /**
   * Constructs a new UdfContent object.
   *
   * @param \Drupal\languagewire_translation_provider\api\Libraries\Content\Udf\UniversalDocumentInterface $udf
   *   Udf .
   */
  public function __construct(UniversalDocumentInterface $udf) {
    $this->udf = $udf;
    $this->serializer = new DocumentJsonSerializer();
  }

  /**
   * {@inheritDoc}
   */
  public function getStream(): StreamInterface {
    return $this->toStream()->getStream();
  }

  /**
   * {@inheritDoc}
   */
  public function getMimeType(): string {
    return $this->toStream()->getMimeType();
  }

  /**
   * Get Udf .
   */
  public function getUdf(): UniversalDocumentInterface {
    return $this->udf;
  }

  /**
   * To Stream .
   */
  private function toStream(): ContentInterface {
    if (!isset($this->stream)) {
      $stream = new Stream('php://temp/', 'wb+');
      $stream->write($this->toJsonString());
      $stream->rewind();
      $this->stream = new StreamContent($stream, MediaType::UDF);
    }

    return $this->stream;
  }

  /**
   * To Json String .
   */
  private function toJsonString(): string {
    return $this->serializer->serialize($this->udf);
  }

}
