<?php

namespace Drupal\languagewire_translation_provider\Content;

/**
 * TMGMT Content.
 */
final class TMGMTContent {

  /**
   * Content ID.
   *
   * @var string
   */
  private string $contentId;

  /**
   * Content.
   *
   * @var string
   */
  private mixed $content;

  /**
   * Label.
   *
   * @var string
   */
  private string $label;

  /**
   * Constructs a new TMGMTContent object.
   *
   * @param string $contentId
   *   Content ID.
   * @param array $content
   *   Content.
   */
  public function __construct(string $contentId, array $content) {
    $this->contentId = $contentId;
    $this->content = $content['#text'];
    $this->label = $this->contentLabel($content);
  }

  /**
   * Content ID.
   */
  public function getContentId(): string {
    return $this->contentId;
  }

  /**
   * Sanitized content ID.
   */
  public function getSanitizedContentId(): string {
    return str_replace(['[', ']'], '_', $this->contentId);
  }

  /**
   * Content.
   */
  public function getText(): string {
    return $this->content;
  }

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

  /**
   * Sanitize.
   */
  public function sanitize(SanitizerInterface $sanitizer): self {
    $clone = clone $this;
    $clone->content = $sanitizer->sanitize($this->content);

    return $clone;
  }

  /**
   * Desanitize.
   */
  private function contentLabel(array $content): string {
    if (isset($content['#label'])) {
      return $content['#label'];
    }

    if (isset($content['#parent_label'])) {
      return current($content['#parent_label']);
    }

    return "ID: $this->contentId";
  }

}
