import { exec } from 'child_process';

export const runCallback = function(fn: Function, thisArg: any) {
	return new Promise(function(resolve, reject) {
		fn.call(thisArg, function(error: Error) {
			if (error) {
				reject(error);
			} else {
				if (arguments.length === 0) {
					resolve();
				} else if (arguments.length === 1) {
					resolve(arguments[1]);
				} else {
					resolve(Array.prototype.slice.call(arguments, 1));
				}
			}
		});
	});
};

export const promiseFromCallback = function(fn: Function, thisArg: any, ...args: any[]) {
	return Promise.resolve().then(function() {
		args.unshift(undefined);

		fn = fn.bind.apply(fn, args);

		return runCallback(fn, thisArg);
	});
};

export default function(cmd: string, opts = { env: {} }) {
	return new Promise((resolve, reject) => {
		opts.env = Object.assign({}, { PATH: `${process.env.PATH}:/var/task/bin` }, opts.env);
		exec(cmd, opts, (error, stdout, stderr) => {
			if (error) {
				reject(error);
			} else {
				resolve({ stdout, stderr });
			}
		});
	});
}

export interface BotParams {
	channel_id: string;
	team_id: string;
	message_ts: string;
}

export const makeBotId = ({ channel_id, team_id, message_ts }: BotParams) => {
	let chunks = [team_id, channel_id];
	if (message_ts) {
		chunks.push(message_ts);
	}
	return chunks.filter((chunk) => chunk).join('/');
};
