<?php

namespace Drupal\pagedesigner\Plugin\pagedesigner\Handler;

use Drupal\Core\Render\Element as RenderElement;
use Drupal\pagedesigner\Entity\Element;
use Drupal\pagedesigner\Plugin\CompoundHandlerBase;

/**
 * Process entities of type "row".
 *
 * @PagedesignerHandler(
 *   id = "row",
 *   name = @Translation("Row render"),
 *   types = {
 *     "row",
 *   },
 * )
 */
class Row extends CompoundHandlerBase {

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

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

  /**
   * {@inheritdoc}
   */
  public function view(Element $entity, string $view_mode, array &$build = []) {
    parent::view($entity, $view_mode, $build);
    $children = $this->collectChildren($entity, $view_mode);
    foreach ($children as $key => $child) {
      $build[$key] = $this->viewBuilder->view($child, $view_mode);
    }
    $build['#pre_render'][] = [$this->viewBuilder, 'render'];
  }

  /**
   * {@inheritdoc}
   */
  public function build(Element $entity, string $view_mode, array &$build = []) {
    parent::build($entity, $view_mode, $build);
    $children = RenderElement::children($build);
    $fields = [];
    foreach ($children as $key) {
      $child = $build[$key]['#pagedesigner_element'];
      $placeholder = $child->field_placeholder->value;
      if ($child->bundle() == 'cell') {
        // For cells, add field with reference to renderable child.
        $fields[$placeholder] = &$build[$key];
      }
      else {
        // For value types, build the child and add the result to the field.
        $fields[$placeholder] = $this->subBuild($child, $view_mode, $build);
      }
    }
    $build['#fields'] = $fields;
    $build = [
      'pagedesigner_structure' => $build,
    ];
  }

}
