<?php

namespace Drupal\pagedesigner\Plugin;

use Drupal\pagedesigner\Entity\Element;

/**
 * Povides the field handler base class pagedesigner elements.
 *
 * The field handler provides methods for handling trait pagedesigner elements.
 * It is to be extended and the inherited class
 * to be annotated for the correct type of pagedesiger element.
 */
class FieldHandlerBase extends HandlerPluginBase {

  /**
   * {@inheritdoc}
   */
  public function serialize(Element $entity, array &$result = []) {
    $value = $this->elementHandler->get($entity);
    $result = [$value] + $result;
  }

  /**
   * {@inheritdoc}
   */
  public function generate($definition, array $data, ?Element &$entity = NULL) {
    parent::generate($definition, $data, $entity);
    $entity->field_placeholder->value = $data['placeholder'];
    $entity->parent->target_id = $data['parent'];
    $entity->container->target_id = $data['container'];
    $entity->entity->target_id = $data['entity'];
    if (!empty($data)) {
      $this->elementHandler->patch($entity, $data);
    }
    else {
      $entity->saveEdit();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function view(Element $entity, string $view_mode, array &$build = []) {
  }

  /**
   * {@inheritdoc}
   */
  public function build(Element $entity, string $view_mode, array &$build = []) {
    $value = $this->elementHandler->get($entity);
    $build = ['#markup' => ''] + $build;
    if (!empty($value) || strlen($value)) {
      $build['#markup'] = $value;
    }
  }

}
