<?php

declare(strict_types=1);

namespace Drupal\Tests\lms_xapi\FunctionalJavascript;

use Drupal\Core\Url;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
use Drupal\Tests\lms\LmsTestHelperTrait;

/**
 * General javascript test of LMS basic features.
 *
 * @group lms
 */
final class LmsXapiTest extends WebDriverTestBase {

  use LmsTestHelperTrait;

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'claro';

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'dblog',
    'page_cache',
    'dynamic_page_cache',
    'block',
    'lms',
    'lms_xapi',
    'lms_xapi_activity',
    'lrs_xapi',
  ];

  /**
   * Test user data.
   *
   * Phpstan is wrong, this property is getting written to in
   * LmsTestHelperTrait::setSourceData().
   *
   * @phpstan-ignore property.onlyRead
   */
  private array $userData;

  /**
   * Test user accounts.
   */
  private array $users = [];

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

    // Set source data.
    $this->setSourceData();

    // Import test config.
    $this->importTestConfig();

    // Create test users.
    foreach ($this->userData as $name => $values) {
      $this->users[$name] = $this->drupalCreateUser([], NULL, FALSE, $values);
    }

    // Add Xapi admin permission to lms_admin role.
    $role = $this->container->get('entity_type.manager')->getStorage('user_role')->load('lms_admin');
    $role->grantPermission('administer xapi')->save();
  }

  /**
   * Tests that the site can be installed with the modules installed.
   */
  public function testXapiActivity(): void {
    $page = $this->getSession()->getPage();
    $assert_session = $this->assertSession();

    $this->drupalLogin($this->users['admin']);
    $this->drupalGet(Url::fromRoute('entity.lms_activity_type.collection'));
    $page->clickLink('Add activity type');
    $this->setFormElementValue('input', 'name', 'xapi');
    $this->setFormElementValue('select', 'pluginId', 'xapi');
    $page->pressButton('edit-submit');
    $assert_session->pageTextContains('xapi');

    $this->drupalLogin($this->users['teacher']);
    $this->drupalGet(Url::fromRoute('entity.lms_activity.add_form', [
      'lms_activity_type' => 'xapi',
    ]));
    $this->setFormElementValue('input', 'name[0][value]', 'Xapi activity');
  }

}
