<?php

namespace Drupal\Tests\pagedesigner\Kernel\HandlerTests;

/**
 * Base class to test a compound handler with a predefined entity defintion.
 *
 * Tests serializing, getting and rendering of the entity.
 *
 * @group pagedesigner
 */
abstract class CompoundHandlerTestBase extends HandlerTestBase {

  /**
   * {@inheritDoc}
   */
  protected function internalViewTest() {
    $build = parent::internalViewTest();
    $this->assertTrue(!empty($build['#pre_render']) || !empty($build['#lazy_builder']) || !empty($build['#pagedesigner_entity']));
    if (!empty($build['#lazy_builder'])) {
      $this->assertCount(2, $build);
    }
    return $build;
  }

  /**
   * {@inheritDoc}
   */
  protected function internalBuildTest() {
    $build = parent::internalBuildTest();
    if (!empty($build['#pagedesigner_entity'])) {
      $this->assertTrue($build['#pagedesigner_entity']->id() == $this->entity->id());
    }
    return $build;
  }

  /**
   * {@inheritDoc}
   */
  protected function editBuildTest() {
    $build = parent::editBuildTest();
    if (!empty($build['#type']) && $build['#type'] == 'pattern') {
      $this->assertTrue(!empty($build['#pagedesigner_entity']));
      $this->assertTrue(!empty($build['#pagedesigner_edit']));
      $this->assertTrue($build['#pagedesigner_entity']->id() == $this->entity->id());
    }
    elseif (!empty($build['#type']) && $build['#type'] == 'inline_template') {
      $this->assertTrue(!empty($build['#template']));
      $this->assertTrue(str_contains((string) $build['#template'], 'data-entity-id="{{id}}"'));
      $this->assertTrue(str_contains((string) $build['#template'], 'id="{{html_id}}"'));
      $this->assertTrue(str_contains((string) $build['#template'], (string) ('data-gjs-type="' . $this->handlerId)));
      $this->assertTrue($build['#context']['id'] === $this->entity->id());
      $this->assertTrue($build['#context']['html_id'] === 'pd-cp-' . $this->entity->id());
    }
    elseif (!empty($build['#prefix'])) {
      $this->assertTrue(str_contains((string) $build['#prefix'], 'data-entity-id="' . $this->entity->id() . '"'));
      $this->assertTrue(str_contains((string) $build['#prefix'], 'id="pd-cp-' . $this->entity->id() . '"'));
      $this->assertTrue(str_contains((string) $build['#prefix'], (string) ('data-gjs-type="' . $this->handlerId)));
    }

    return $build;
  }

}
