const { spawn } = require('child_process');
let iconv = null;
try {
	iconv = require('iconv-lite');
} catch (error) {

}
var spawnArr = [];//记录打开其他程序的对象
exports.OpenEXE = (path) => {
	try {
		if (process.platform == 'darwin') {
			var childSpawn = spawn(path + "/Contents/MacOS/Electron", [path], {
				stdio: 'ignore',
			});
			spawnArr[spawnArr.length] = { "id": childSpawn, "type": 0 };
			return path + "/Contents/MacOS/Electron";
		} else {
			var childSpawn = spawn(path);
			spawnArr[spawnArr.length] = { "id": childSpawn, "type": 0 };
			return spawnArr.length - 1;
		}
	} catch (error) {
		return -1;
	}
}
exports.KillEXE = (kill) => {
	try {
		if (spawnArr[kill]["type"] == 0) {
			spawnArr[kill]["id"].kill();
			spawnArr[kill]["type"] = -1;
		}
	} catch (error) {

	}
}
exports.DoesTheProcessExist = (query, cb, encoding = "GBK") => {
	const execs = require('child_process').exec;
	let platform = process.platform;
	let cmd = '';
	switch (platform) {
		case 'win32': cmd = `tasklist`; break;
		case 'darwin': cmd = `ps -ax | grep ${query}`; break;
		case 'linux': cmd = `ps -A`; break;
		default: break;
	}
	let cwd = {
		cwd: "",
		encoding: "GBK",
	}
	execs(cmd, cwd, (err, stdout, stderr) => {
		try {
			const utf8Stdout = iconv.decode(Buffer.from(stdout, 'binary'), encoding);
			if (cmd.indexOf("ps -ax |") != -1) {
				cb(utf8Stdout.toLowerCase().indexOf(query.toLowerCase()) > -1 && utf8Stdout.toLowerCase().indexOf("applications") > -1);
			} else {
				cb(utf8Stdout.toLowerCase().indexOf(query.toLowerCase()) > -1);
			}
		} catch (error) {
			cb(false)
		}

	});
}

