const
	util = require('util'),
	spawn = require('child_process').spawn,
	success = ['success', 'D/DroidGap', 'D/CordovaLog'],
	error = ['error', 'E/', 'E native'],
	warning = ['warning', 'W/Web Console']

module.exports = (command, consumers) => {
	const
		on_error = data => data.toString().split('\n').forEach(line =>
			consumers.forEach(consumer => consumer.error(line))
		),
		args = command.split(' '),
		logcat = spawn(args.shift(), args)

	logcat.stdout.on('data', data => data
		.toString()
		.split('\n')
		.map(line => [
	        line,
	        error.some(_ => line.includes(_))
	            ? 'error'
	            : warning.some(_ => line.includes(_))
	                ? 'warning'
	                : success.some(_ => line.includes(_))
	                    ? 'success'
	                    : 'info'
		])
		.forEach(([line, type]) =>
			consumers.forEach(consumer =>
				consumer[type](line)
			)
		)
	)

	logcat.stderr.on('data', on_error)
	logcat.on('error', on_error)
}
