<?php

namespace Drupal\Tests\lingotek\Functional;

use Drupal\Tests\BrowserTestBase;

/**
 * Tests the Lingotek dashboard.
 *
 * @group lingotek
 */
class LingotekAccountTest extends BrowserTestBase {

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

  /**
   * Modules to install.
   *
   * @var array
   */
  protected static $modules = ['lingotek', 'lingotek_test'];

  /**
   * Tests that the dashboard cannot be accessed without a valid user.
   */
  public function testAccountCanConnect() {
    \Drupal::state()->set('must_remain_disconnected', TRUE);

    $assert_session = $this->assertSession();

    // Login as admin.
    $this->drupalLogin($this->rootUser);
    // Try to navigate to the Dashboard page, and assert we are redirected.
    $this->drupalGet('admin/lingotek/setup/account');
    // Fake the connection to an account in Lingotek.
    $this->clickLink('Setup Token');
    $this->submitForm(['access_token' => 'test_token'], 'Save Token');
    // Our fake backend generates a token, returns to the site, completes the
    // handshake and return some fake data.
    $this->assertSession()->pageTextContains('Your account settings have been saved.');
    // Then we can select the defaults for the different fields.
    $this->submitForm(['community' => 'test_community'], 'Next');
    $this->assertSession()->pageTextContains('The configuration options have been saved.');
    $this->submitForm([
      'project' => 'test_project',
      'vault' => 'test_vault',
      'workflow' => 'test_workflow',
    ], 'Save configuration');
    $this->assertSession()->pageTextContains('The configuration options have been saved.');
    // We are done with the defaults, we should be redirected to the dashboard.
    $this->assertSession()->pageTextContains('Dashboard');
    $this->assertSession()->addressEquals('admin/lingotek');
  }

  /**
   * Tests that the dashboard cannot be accessed without a valid user.
   */
  public function testDashboardIsNotAvailableBeforeConnecting() {
    \Drupal::state()->set('must_remain_disconnected', TRUE);

    $assert_session = $this->assertSession();

    // Login as admin.
    $this->drupalLogin($this->rootUser);

    // Try to navigate to the Dashboard page, and assert we are redirected.
    $this->drupalGet('admin/lingotek');
    $this->assertSession()->addressEquals('admin/lingotek/setup/account');
    $assert_session->linkExists('Setup Token');
  }

}
