const path = require('path');
const { exec } = require('child_process');
const nodeWindows = require('node-windows');
const nodeWindowsService = nodeWindows.Service;

const posBackendFolder = 'C:/PointOfSales/POSBackend';

const litPosSoftware = new nodeWindowsService({
	name: 'LitPosSoftware',
	script: path.join(posBackendFolder, 'index.js')
});

litPosSoftware.on('start', () => {
	console.log('LitPosSoftware service started.');
});

litPosSoftware.on('stop', () => {
	console.log('LitPosSoftware service stoped.');
});

litPosSoftware.on('install', () => {
	console.log('LitPosSoftware service installed.');
	litPosSoftware.start();
});

litPosSoftware.on('alreadyinstalled', () => {
    console.log('LitPosSoftware service already installed.');
	litPosSoftware.start();
});

litPosSoftware.on('uninstall', () => {
	console.log('LitPosSoftware service uninstalled.');
});

nodeWindows.list((services) => {
	const lps = services.filter(s => ['litpossoftware.exe', 'node.exe'].includes(s.ImageName) && 'Services' == s.SessionName);
	if (typeof process.argv[2] != 'undefined') {
		litPosSoftware.uninstall();
	} else {
		litPosSoftware.install();
		if (lps.length > 0) {
			console.log('LitPosSoftware service started.');
			const killLitPosSoftware = exec('taskkill /fi "IMAGENAME eq node.exe" /f /t', {cwd: posBackendFolder}, (error, stdout, stderr) => { });
		}
	}
}, true);
