<?php

namespace Drupal\pagedesigner\Plugin\pagedesigner\Handler;

use Drupal\Core\Render\Markup;
use Drupal\pagedesigner\Entity\Element;
use Drupal\pagedesigner\Plugin\HandlerConfigTrait;

/**
 * Process entities of type "longtext".
 *
 * @PagedesignerHandler(
 *   id = "longtext",
 *   name = @Translation("Longtext renderer"),
 *   types = {
 *     "longtext"
 *   },
 * )
 */
class Longtext extends Content {

  // Import config property and setter, auto set in HandlerConfigTrait::create.
  use HandlerConfigTrait;

  /**
   * {@inheritdoc}
   */
  public function get(Element $entity, string &$result = '') {
    // Remove comments from style tags to prevent breaking css parsing.
    $value = \preg_replace_callback('/(<style.*?)<!-+(.*?)\/*-+>(.*?<\/style>)/s', fn($matches) => $matches[1] . $matches[2] . $matches[3], (string) $entity->field_content->value);
    $result .= Markup::create($value);
  }

  /**
   * {@inheritdoc}
   */
  public function build(Element $entity, string $view_mode, array &$build = []) {
    $value = $this->elementHandler->get($entity);
    $format = $this->configFactory->get('pagedesigner.settings')->get('filter_format_longtext');
    if (empty($format)) {
      $format = 'plain_text';
    }
    $build = [
      '#type' => 'processed_text',
      '#text' => (string) $value,
      '#format' => $format,
      '#filter_types_to_skip' => [],
      '#langcode' => $entity->langcode->value,
    ] + $build;
  }

}
