<?php

namespace Drupal\Tests\pagedesigner_link\Kernel\HandlerTests;

use Drupal\node\Entity\Node;
use Drupal\Tests\pagedesigner\Kernel\HandlerTests\PlainFieldHandlerTestBase;

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

  /**
   * Define the properties of the entity.
   *
   * @var array
   */
  protected $entityDefinition = [
    'type' => 'link',
    'name' => 'link',
    'langcode' => 'en',
    'field_link' => [
      'uri' => '/node/',
      // 'uri' => 'http://www.example.com/some/url',
      'title' => 'link title',
    ],
  ];

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

  /**
   * {@inheritdoc}
   */
  public function setUp(): void {
    self::$modules[] = 'system';
    self::$modules[] = 'link';
    self::$modules[] = 'linkit';
    self::$modules[] = 'pagedesigner_link';
    self::$modules[] = 'path_alias';
    parent::setUp();
    $this->installEntitySchema('node');
    $this->installEntitySchema('path_alias');
    $this->installConfig([
      'path_alias', 'node', 'link', 'linkit', 'pagedesigner_link',
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function assertPreConditions(): void {
    parent::assertPreConditions();
    $node = Node::create(['title' => 'test node', 'type' => 'test']);
    $node->save();
    $this->entity->field_link->uri .= $node->id();
    $this->entityDefinition['field_link']['uri'] .= $node->id();
  }

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

  /**
   * {@inheritdoc}
   *
   * Additionally, assert the returned value is equal to the given value.
   */
  protected function serializeTest() {
    $result = parent::serializeTest();
    $this->assertTrue($result['uri'] == $this->entityDefinition['field_link']['uri']);
    $this->assertTrue($result['title'] == $this->entityDefinition['field_link']['title']);
    return $result;
  }

  /**
   * {@inheritdoc}
   *
   * Also assert the returned value is equal to the processed given value.
   */
  protected function getTest() {
    $value = parent::getTest();
    $this->assertTrue($value == '/en' . \Drupal::service('path_alias.manager')->getAliasByPath($this->entityDefinition['field_link']['uri'], 'en'));
    return $value;
  }

  /**
   * {@inheritdoc}
   */
  protected function internalBuildTest() {
    $build = parent::internalBuildTest();
    $this->assertTrue($build['#plain_text'] == '/en' . \Drupal::service('path_alias.manager')->getAliasByPath($this->entityDefinition['field_link']['uri'], 'en'));
    return $build;
  }

}
