<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\api\Libraries\Content\Serialize;

use Drupal\languagewire_translation_provider\api\Libraries\Content\DehydrationInterface;
use Drupal\languagewire_translation_provider\api\Libraries\Content\JsonCodec;
use Drupal\languagewire_translation_provider\api\Libraries\Content\SerializerInterface;
use Drupal\languagewire_translation_provider\api\Libraries\Content\Udf\UniversalDocumentFactory;
use Drupal\languagewire_translation_provider\api\Libraries\Content\Udf\UniversalDocumentInterface;

/**
 * Serializer and deserializer for Universal Documents into a JSON format.
 *
 * Serializer will create a valid Universal Document Format (UDF) JSON string.
 * Deserializer will turn JSON string into a new Universal Document.
 */
final class DocumentJsonSerializer implements SerializerInterface {

  /**
   * Serializes a Universal Document into a JSON string.
   *
   * @param \Drupal\languagewire_translation_provider\api\Libraries\Content\DehydrationInterface $object
   *   The object to serialize.
   */
  public function serialize(DehydrationInterface $object): string {
    return JsonCodec::encode($object->dehydrate());
  }

  /**
   * Deserializes a JSON string into a Universal Document.
   *
   * @param string $data
   *   The JSON string to deserialize.
   *
   * @return \Drupal\languagewire_translation_provider\api\Libraries\Content\Udf\UniversalDocumentInterface
   *   The deserialized Universal Document.
   *
   * @throws \Drupal\languagewire_translation_provider\api\Libraries\Content\Udf\FrameMissingTextException
   */
  public function deserialize(string $data): UniversalDocumentInterface {
    $documentData = JsonCodec::decode($data);

    return UniversalDocumentFactory::create($documentData);
  }

}
