<?php

namespace Drupal\pagedesigner\Tests\Kernel\Services;

use Drupal\Component\Serialization\Json;
use Drupal\KernelTests\KernelTestBase;
use Drupal\pagedesigner\ElementViewBuilder;
use Drupal\pagedesigner\Entity\Element;
use Drupal\Tests\user\Traits\UserCreationTrait;

/**
 * Tests for ElementViewBuilder service.
 */
class ElementViewBuilderTest extends KernelTestBase {
  use UserCreationTrait;

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'pagedesigner',
    'ui_patterns',
    'user',
    'node',
    'field',
    'taxonomy',
    'text',
    'editor',
    'rest',
    'serialization',
  ];

  /**
   * The service being tested.
   *
   * @var object
   */
  protected $service = NULL;

  /**
   * Set up environment for Kernel testing.
   *
   * Set up current user, install config and schema for pagedesigner elements.
   */
  public function setUp(): void {
    parent::setUp();
    $this->service = $this->container->get('entity_type.manager')->getViewBuilder('pagedesigner_element');
    $this->setUpCurrentUser();
    $this->installEntitySchema('pagedesigner_element');
    $this->installConfig(['pagedesigner']);
  }

  /**
   *
   */
  public function testLazyBuilder() {
    $entity = Element::create([
      'type' => 'component',
      'name' => 'Component',
    ]);
    $entity->save();
    $build = [
      '#pagedesigner_element' => $entity,
      '#view_mode' => ElementViewBuilder::RENDER_MODE_INTERNAL,
      '#theme' => 'pagedesigner_element',
      '#cache' => [
        'max-age' => -1,
      ],
      '#weight' => 0,
    ];
    $arguments = [
      '#entity_id' => $entity->id(),
      '#view_mode' => ElementViewBuilder::RENDER_MODE_INTERNAL,
      '#cache' => [
        'max-age' => -1,
      ],
    ];
    $this->service->addLazyBuilder($entity, ElementViewBuilder::RENDER_MODE_INTERNAL, $build);
    // Check size (only weight and lazy_builder)
    $this->assertCount(2, $build);
    // Check lazy_builder.
    $this->assertArrayHasKey('#lazy_builder', $build);
    $this->assertEquals(['\Drupal\pagedesigner\ElementViewBuilder::lazyBuilder', [Json::encode($arguments)]], $build['#lazy_builder']);

    // Check weight.
    $this->assertArrayHasKey('#weight', $build);
    $this->assertEquals(0, $build['#weight']);
  }

}
