<?php

namespace Drupal\Tests\pagedesigner\Kernel\HandlerTests;

use Drupal\Component\Utility\Crypt;
use Drupal\Core\Site\Settings;

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

  /**
   * {@inheritdoc}
   */
  protected $handlerId = 'autocomplete';

  /**
   * {@inheritdoc}
   */
  protected $entityDefinition = [
    'type' => 'content',
    'name' => 'autocomplete',
    'langcode' => 'en',
    'field_content' => ['value' => '[]'],
  ];

  /**
   * {@inheritdoc}
   */
  protected $fieldDefinition = [
    'name' => 'autocomplete',
    'label' => 'autocomplete',
    'type' => 'autocomplete',
    'additional' => [
      'autocomplete' => [
        'entity_type' => 'node',
        'bundles' => 'page',
        'field' => 'title',
      ],
    ],
  ];

  /**
   * {@inheritdoc}
   */
  protected function prepareTest() {
    $fieldArray = parent::prepareTest();
    $additionalDefinition = $this->patternDefinitionField->getAdditional();
    $selection_settings = [
      'target_bundles' => ($additionalDefinition['autocomplete']['bundles']) ?: NULL,
      'sort' => ['field' => "_none", 'direction' => 'ASC'],
      'auto_create' => FALSE,
      'auto_create_bundle' => '',
      'match_operator' => 'CONTAINS',
      'match_limit' => 10,
    ];
    $entityType = $additionalDefinition['autocomplete']['entity_type'];
    $data = serialize($selection_settings) . $entityType . 'default:' . $entityType;
    $selection_settings_key = Crypt::hmacBase64($data, Settings::getHashSalt());

    // Assert that the fieldArray has the expected values.
    $this->assertEquals(
      '/entity_reference_autocomplete/node/default:node/' . $selection_settings_key,
      $fieldArray['additional']['autocomplete_href']
    );
    return $fieldArray;
  }

}
