import { spawn } from 'node:child_process';

export class PageServer {

	constructor(fallback, port) {
		this.process = null
		this.fallback = fallback
		this.port = port
		this.exited = null
	}

	async start() {
		if (this.process) throw new Error('Server already running');

		this.process = spawn('node_modules/.bin/esbuild', [
			'src/*.js',
			'src/*.mjs',
			'--watch',
			'--servedir=tests/',
			'--outdir=tests/js/',
			'--out-extension:.js=.mjs',
			`--serve-fallback=${this.fallback}`,
			`--serve=${this.port}`
		]);

		await new Promise((started, start_failed) => {
			this.exited = new Promise(async (resolve_exited) => {
				let stderr = '';
				for await (const chunk of this.process.stderr) {
					//console.log(chunk.toString())
					if (stderr !== null) {
						stderr += chunk.toString();
						if (stderr.includes('build finished')) {
							console.log(`PageServer running:  ${this.fallback}@${this.port}`);
							stderr = null;
							started()
						}
					}
				}
				if (stderr !== null) start_failed(new Error('Server process exited before printing "build finished"'))
				this.process.on('exit', (code) => {
					console.log(`PageServer exited:  ${this.fallback}@${this.port}`)
					resolve_exited(code)
				})
			})
		})
	}

	async stop() {
		if (this.process) {
			this.process.kill();
			await this.exited;
			this.process = null;
		}
	}
}
