<?php

namespace Drupal\pagedesigner\Plugin\DataType;

use Drupal\Core\TypedData\TypedData;
use Drupal\pagedesigner\Entity\Element;

/**
 * A computed property for pagedesigner content data.
 *
 * @DataType(
 *   id = "pagedesigner_item_data",
 *   label = @Translation("Pagedesigner content data"),
 *   description = @Translation("Generated content of the pagedesigner."),
 * )
 */
class PagedesignerData extends TypedData {

  /**
   * Cached processed text.
   *
   * @var array|null
   */
  protected $value = NULL;

  /**
   * {@inheritdoc}
   */
  public function getValue() {
    if ($this->value == NULL) {
      $language = $this->getParent()->getEntity()->language()->getId();
      $this->value = $this->getContent($this->getParent()->target_id, $language);
    }
    return $this->value;
  }

  /**
   * Returns the text content of the tree as a list.
   *
   * @param int $root_id
   *   The id of the root element.
   * @param string $langcode
   *   The desired language.
   * @param bool $published
   *   Whether to return the published or editing text.
   *
   * @return string
   *   The text content of the tree.
   */
  public function getContent(int $root_id, string $langcode, bool $published = TRUE) {
    $content = [];
    $root = Element::load($root_id);
    if ($root != NULL) {
      $root = ($published) ? $root->loadNewestPublished() : $root;
      if ($root != NULL && $root->hasTranslation($langcode)) {
        $list = [];
        $root = $root->getTranslation($langcode);
        $content = \Drupal::service('pagedesigner.service.element_handler')
          ->getContent($root, $list, $published);
      }
    }
    return $content;
  }

  /**
   * {@inheritdoc}
   */
  public function getString() {
    return implode(' ', $this->getValue());
  }

}
