'use strict';

// Packages
const test = require('ava');

// Ours
require('./helpers/nodecg-and-webdriver')(test, { // Must be first.
	tabs: ['login'],
	nodecgConfigName: 'nodecg-login.json'
});
const C = require('./helpers/test-constants');
const e = require('./helpers/test-environment');

test.serial('redirects unauthorized users to /login', async t => {
	await e.browser.client.newWindow(C.DASHBOARD_URL);
	const url = await e.browser.client.getUrl();
	t.is(url, C.LOGIN_URL);
});

test.serial('should deny access to bad credentials', async t => {
	await e.browser.client.switchTab(e.browser.tabs.login);

	await e.browser.client.waitForVisible('#username');
	await e.browser.client.waitForVisible('#localForm');
	await e.browser.client.waitForVisible('#password');

	await e.browser.client.setValue('#username', 'admin');
	await e.browser.client.setValue('#password', 'wrong_password');
	await e.browser.client.click('#localSubmit');

	const url = await e.browser.client.getUrl();
	t.is(url, C.LOGIN_URL);
});

test.serial('logging in should work', async t => {
	await e.browser.client.switchTab(e.browser.tabs.login);

	await e.browser.client.waitForVisible('#username');
	await e.browser.client.waitForVisible('#localForm');
	await e.browser.client.waitForVisible('#password');

	await e.browser.client.setValue('#username', 'admin');
	await e.browser.client.setValue('#password', 'password');
	await e.browser.client.click('#localSubmit');

	const url = await e.browser.client.getUrl();
	t.is(url, C.DASHBOARD_URL);
});

test.serial('logging out should work', async t => {
	await e.browser.client.newWindow(`${C.ROOT_URL}logout`);
	const url = await e.browser.client.getUrl();
	t.is(url, C.LOGIN_URL);
});

@@ -1514,32 +1514,942 @@
 OARD_URL);%0A%7D);%0A%0A
+test.serial('regenerating a token should send the user back to /login', async t =%3E %7B%0A%09await e.browser.client.switchTab(e.browser.tabs.login);%0A%0A%09t.is(await e.browser.client.getUrl(), C.DASHBOARD_URL);%0A%0A%09// We need to preserve the coverage from this test, because it will be lost%0A%09// when the page is redirected to /login.%0A%09const %7Bvalue: coverage%7D = await e.browser.client.executeAsync(async done =%3E %7B%0A%09%09const ncgSettings = document.querySelector('ncg-dashboard').shadowRoot%0A%09%09%09.querySelector('ncg-settings');%0A%09%09await ncgSettings.resetKey();%0A%09%09done(window.__coverage__);%0A%09%7D);%0A%0A%09await e.browser.client.waitUntil(async () =%3E %7B%0A%09%09const url = await e.browser.client.getUrl();%0A%09%09return url === C.LOGIN_URL;%0A%09%7D, 5000);%0A%0A%09// Put our preserved coverage back on the page for later extraction.%0A%09await e.browser.client.execute(injectedCoverage =%3E %7B%0A%09%09window.__coverage__ = injectedCoverage;%0A%09%7D, coverage);%0A%0A%09t.pass();%0A%7D);%0A%0A
 test.serial('log

add test for regenerateToken