import { join } from 'path';
import { WebServer } from './WebServer/WebServer';
import { homedir } from 'os';
import {
	Config,
	ConfigurationManager,
} from './Configuration/ConfigurationManager';
import { CameraRunner } from './CameraRunner';
import { UnityRunner } from './Unity/UnityRunner';
import { UnityWebSocket } from './Unity/UnityWebSocket';

export class Main {
	dataPath = join(homedir(), 'MorphixProductions', 'NTSHControl');

	ConfigurationManager = new ConfigurationManager(this);
	WebServer = new WebServer(this);

	CameraRunner = new CameraRunner(this);
	UnityRunner = new UnityRunner(this);
	UnityWebSocket = new UnityWebSocket(this);

	Config: Config;

	async start() {
		await this.ConfigurationManager.load();
		await this.WebServer.listen();

		await this.CameraRunner.connect();

		setTimeout(() => {
			this.UnityRunner.start();
		}, this.Config.unity.executable.startUpDelay ?? 0);
	}

	async restart() {
		console.log('Stopping UnityRunner...');
		await this.UnityRunner.stop();

		const doReboot = !process.argv.includes('--no-reboot');
		console.log(`${doReboot ? 'Rebooting' : 'Restarting'} CameraRunner...`);
		const succeed = await new Promise((resolve) => {
			this.CameraRunner.sendCommand(
				doReboot ? 'reboot' : 'restart',
				(response: { succeed: boolean; message?: string }) => {
					if (!response.succeed) {
						console.error(
							'Failed to reboot CameraRunner:',
							response.message
						);
						resolve(false);
					} else {
						console.log('CameraRunner rebooted successfully.');
						resolve(true);
					}
				}
			);
		});
		if (!succeed) return;

		console.log('Starting UnityRunner...');
		await this.UnityRunner.start();

		console.log('Restart complete.');
	}
}
