import { BackendServer } from './backend-server.mjs'
import { PageServer } from './test-page-server.mjs'


async function assert_success(browser, target_id) {
	await browser.waitUntil(async () => { return (await (await browser.$(target_id)).getText()) != '-' })
	const result = await (await browser.$(target_id)).getText()
	if (result != 'OK') {
		const error = JSON.parse(result)
		console.log("\x1b[31mERROR\x1b[0m")
		console.error(`\x1b[31m${error.message}\x1b[0m`)
		console.log("Stack:")
		console.log(error.stack)
		throw "Error on the browser side"
	}
}

export async function test_navigation_unit(browser, headfull) {
	const server = new PageServer('tests/dynamic-browser.html', 8008)
	await server.start()

	const backend = new BackendServer(3003)
	await backend.start()

	await browser.url('http://127.0.0.1:8008/unit-browser.html')
	//await browser.keys(['F12']);
	//await browser.execute(() => { document.dispatchEvent(new KeyboardEvent('keydown', { key: 'F12' })) })

	try {
		await assert_success(browser, '#state_result')
		await assert_success(browser, '#state_diff_result')
		await assert_success(browser, '#state_url_result')
		await assert_success(browser, '#state_registry_result')
		await assert_success(browser, '#remote_result')
	} catch (error) {
		console.error(error)
		if (headfull) await browser.debug()
		throw error
	} finally {
		await server.stop()
		await backend.stop()
	}

}
