<?php

namespace Drupal\pagedesigner\Plugin\pagedesigner\Handler;

use Drupal\pagedesigner\Entity\Element;
use Drupal\pagedesigner\Plugin\CompoundHandlerBase;

/**
 * Process entities of type "component".
 *
 * @PagedesignerHandler(
 *   id = "component",
 *   name = @Translation("Component renderer"),
 *   types = {
 *     "component",
 *   },
 * )
 */
class Component extends CompoundHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function serialize(Element $entity, array &$result = []) {
    parent::serialize($entity, $result);
    $result['type'] = 'component';
  }

  /**
   * {@inheritdoc}
   */
  public function describe(Element $entity, array &$result = []) {
    parent::describe($entity, $result);
    $result['type'] = 'component';
  }

  /**
   * {@inheritdoc}
   */
  public function view(Element $entity, string $view_mode, array &$build = []) {
    parent::view($entity, $view_mode, $build);
    $this->viewBuilder->addLazyBuilder($entity, $view_mode, $build);
  }

  /**
   * {@inheritdoc}
   */
  public function build(Element $entity, string $view_mode, array &$build = []) {
    parent::build($entity, $view_mode, $build);
    $children = $this->collectChildren($entity, $view_mode);
    $fields = [];
    foreach ($children as $child) {
      // Build the child and add the result to the field.
      $fields[$child->field_placeholder->value] = $this->subBuild($child, $view_mode, $build);
    }
    $build['#fields'] = $fields;
    $build = [
      'pagedesigner_component' => $build,
    ];
  }

}
