<?php

namespace Drupal\pagedesigner\Plugin\pagedesigner\Handler;

use Drupal\Component\Serialization\Json;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\pagedesigner\Entity\Element;
use Drupal\pagedesigner\Plugin\PlainFieldHandlerBase;
use Drupal\ui_patterns\Definition\PatternDefinitionField;

/**
 * Process entities of type "multiplecheckbox".
 *
 * @PagedesignerHandler(
 *   id = "multiplecheckbox",
 *   name = @Translation("Multiple checkbox processor"),
 *   types = {
 *      "multiplecheckbox",
 *   }
 * )
 */
class MultipleCheckbox extends PlainFieldHandlerBase {
  use StringTranslationTrait;

  /**
   * {@inheritDoc}
   */
  public function prepare(PatternDefinitionField &$field, &$fieldArray) {
    parent::prepare($field, $fieldArray);
    if (isset($field->toArray()['options']) && \is_array($field->toArray()['options'])) {
      foreach ($field->toArray()['options'] as $key => $option) {
        if (is_string($option)) {
          $option = $this->t($option);
        }
        $fieldArray['options'][$key] = $option;
      }
    }
    if (isset($field->toArray()['value']) && \is_array($field->toArray()['value'])) {
      foreach ($field->toArray()['value'] as $key => $value) {
        $fieldArray['values'][$key] = $value;
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function patch(Element $entity, array $data) {
    if (!empty($data) && is_array($data)) {
      $entity->field_content->value = Json::encode($data);
    }
    else {
      $entity->field_content->value = '';
    }
    $entity->saveEdit();
  }

  /**
   * {@inheritdoc}
   */
  public function serialize(Element $entity, array &$result = []) {
    $value = $this->elementHandler->get($entity);
    if (!empty($value)) {
      $result = Json::decode($value) + $result;
    }
    else {
      $result = Json::decode('');
    }
  }

  /**
   * {@inheritDoc}
   */
  public function generate($definition, array $data, &$entity = NULL) {
    parent::generate(['type' => 'content', 'name' => 'multiplecheckbox'], $data, $entity);
  }

}
