<?php

namespace Drupal\Tests\pagedesigner_svg\Kernel\HandlerTests;

use Drupal\file\Entity\File;
use Drupal\media\Entity\Media;
use Drupal\Tests\pagedesigner_media\Kernel\HandlerTests\MediaHandlerTestBase;

/**
 * Test the "svg" handler with a predefined entity defintion.
 *
 * Tests serializing, getting and rendering of the entity.
 *
 * @group pagedesigner
 */
class SVGHandlerTest extends MediaHandlerTestBase {

  /**
   * Define the properties of the entity.
   *
   * @var array
   */
  protected $entityDefinition = [
    'type' => 'svg',
    'name' => 'svg',
    'langcode' => 'en',
    'field_media' => ['target_id' => 1],
  ];

  /**
   * Define handler to be tested.
   *
   * @var string
   */
  protected $handlerId = 'svg';

  /**
   * {@inheritdoc}
   *
   * @todo Add the pagedesigner editor config to the environment.
   */
  public function setUp(): void {
    self::$modules[] = 'pagedesigner_svg';
    parent::setUp();
    $this->installConfig(['pagedesigner_svg']);
  }

  /**
   * {@inheritdoc}
   */
  public function assertPreConditions(): void {
    parent::assertPreConditions();

    // Create file entity.
    $this->file = File::create([
      'filename' => 'test.svg',
      'uri' => 'public://page/test.svg',
      'status' => 1,
    ]);
    $this->file->save();

    // Create media entity.
    $this->media = Media::create([
      'bundle' => $this->entityDefinition['type'],
      'field_media_file' => ['entity' => $this->file],
    ]);

    $this->entity->field_media->entity = $this->media;
    $this->entityDefinition['field_media']['target_id'] = $this->media->id();
    $this->assertTrue($this->entity->field_media->entity == $this->media);
    $this->assertTrue($this->entityDefinition['field_media']['target_id'] == $this->media->id());
  }

  /**
   * {@inheritdoc}
   *
   * Additionally, assert the returned array contains the pagedesigner library.
   */
  protected function collectAttachmentsTest() {
    $attachments = parent::collectAttachmentsTest();
    $this->assertTrue(\in_array('pagedesigner_svg/pagedesigner', $attachments['library']));
    return $attachments;
  }

  /**
   * {@inheritdoc}
   *
   * Additionally, assert the returned value is equal to the file url.
   */
  protected function getTest() {
    $value = parent::getTest();
    $this->assertTrue($value == $this->file->createFileUrl());
    return $value;
  }

  /**
   * {@inheritdoc}
   *
   * Additionally, assert the returned values
   * are matching the media and the file.
   */
  protected function serializeTest() {
    $result = parent::serializeTest();
    $this->assertTrue($result['src'] == $this->file->createFileUrl());
    return $result;
  }

  /**
   * {@inheritdoc}
   *
   * Additionally, check the render array schema and content.
   */
  protected function internalBuildTest() {
    $build = parent::internalBuildTest();
    $this->assertTrue($build['#plain_text'] == $this->file->createFileUrl());
    return $build;
  }

}
