<?php

namespace src\FunctionalJavascript;

use Drupal\Tests\acquia_dam\FunctionalJavascript\AcquiaDamWebDriverTestBase;
use Drupal\Tests\ckeditor5\Traits\CKEditor5TestTrait;

/**
 * Test DAM media overview.
 *
 * @group acquia_dam_functional_javascript
 * @requires module ckeditor
 */
class DamMediaOverviewTest extends AcquiaDamWebDriverTestBase {

  use CKEditor5TestTrait;

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();

    $this->createMedia();
  }

  /**
   * Create a media entity with DAM asset.
   *
   * @throws \Behat\Mink\Exception\ElementNotFoundException
   * @throws \Behat\Mink\Exception\ExpectationException
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  private function createMedia() {
    $this->createAndLoginContentCreator();
    $this->grantSiteRegistrationToken();
    $this->grantCurrentUserDamToken();

    $this->drupalGet('/node/add/page');
    $this->getSession()->getPage()->fillField('Title', 'Embed Form test');

    $this->waitForEditor();
    $this->pressEditorButton('Insert Media');

    // Check the embedcode form.
    $this->selectAndInsertAsset('f2a9c03d-3664-477c-8013-e84504ed5adc', 'Image', 'original');

    $this->getSession()->switchToIFrame();
    $this->getSession()->getPage()->pressButton('Save');
  }

  /**
   * Tests DAM content overview with dam authenticated user.
   *
   * @throws \Behat\Mink\Exception\ElementNotFoundException
   * @throws \Behat\Mink\Exception\ExpectationException
   */
  public function testDamMediaOverviewAuthenticatedUser() {
    $this->createAndLoginContentCreator();
    $this->grantCurrentUserDamToken();
    $this->drupalGet('/admin/content/dam-media');
    $this->assertSession()->pageTextContains('An asset with many versions.png');
    $this->assertSession()->linkExists('Check for update');
  }

  /**
   * Tests DAM content overview page with non dam authenticated user.
   *
   * @throws \Behat\Mink\Exception\ElementNotFoundException
   * @throws \Behat\Mink\Exception\ExpectationException
   */
  public function testDamMediaOverviewAnonymousUser() {
    $this->createAndLoginContentCreator();
    $this->drupalGet('/admin/content/dam-media');
    $this->assertSession()->pageTextContains('An asset with many versions.png');
    $this->assertSession()->linkNotExists('Check for update');
  }

}
