#!/usr/bin/env node
(function() {

	var fs = require('fs');
	var utf8 = require('utf8');
	var quotedPrintable = require('../quoted-printable.js');
	var strings = process.argv.splice(2);
	var stdin = process.stdin;
	var data;
	var timeout;
	var action;
	var options = {};
	var log = console.log;

	var main = function() {
		var option = strings[0];
		var count = 0;

		if (/^(?:-h|--help|undefined)$/.test(option)) {
			log(
				'quoted-printable v%s - https://mths.be/quoted-printable',
				quotedPrintable.version
			);
			log([
				'\nEncode or decode messages using the `Quoted-Printable` encoding (and UTF-8).',
				'\nUsage:\n',
				'\tquoted-printable [-e | --encode] string',
				'\tquoted-printable [-d | --decode] string',
				'\tquoted-printable [-v | --version]',
				'\tquoted-printable [-h | --help]',
				'\nExamples:\n',
				'\tquoted-printable --encode \'foo = bar ©\'',
				'\techo \'foo =3D bar =C2=A9\' | quoted-printable --decode',
			].join('\n'));
			return process.exit(1);
		}

		if (/^(?:-v|--version)$/.test(option)) {
			log('v%s', quotedPrintable.version);
			return process.exit(1);
		}

		strings.forEach(function(string) {
			// Process options
			if (string == '-e' || string == '--encode') {
				action = 'encode';
				return;
			}
			if (string == '-d' || string == '--decode') {
				action = 'decode';
				return;
			}
			// Process string(s)
			var result;
			if (!action) {
				log('Error: quoted-printable requires at least one option and a string argument.');
				log('Try `quoted-printable --help` for more information.');
				return process.exit(1);
			}
			try {
				if (action == 'encode') {
					result = quotedPrintable.encode(utf8.encode(string, options));
				} else if (action == 'decode') {
					result = utf8.decode(quotedPrintable.decode(string, options));
				}
				log(result);
				count++;
			} catch (exception) {
				log(exception.message + '\n');
				log('Error: failed to %s.', action);
				log('If you think this is a bug in quoted-printable, please report it:');
				log('https://github.com/mathiasbynens/quoted-printable/issues/new');
				log('\nStack trace using quoted-printable@%s:\n', quotedPrintable.version);
				log(exception.stack);
				return process.exit(1);
			}
		});
		if (!count) {
			log('Error: quoted-printable requires a string argument.');
			log('Try `quoted-printable --help` for more information.');
			return process.exit(1);
		}
		// Return with exit status 0 outside of the `forEach` loop, in case
		// multiple strings were passed in.
		return process.exit(0);
	};

	if (stdin.isTTY) {
		// handle shell arguments
		main();
	} else {
		// Either the script is called from within a non-TTY context, or `stdin`
		// content is being piped in.
		if (!process.stdout.isTTY) {
			// The script was called from a non-TTY context. This is a rather uncommon
			// use case we don’t actively support. However, we don’t want the script
			// to wait forever in such cases, so…
			timeout = setTimeout(function() {
				// …if no piped data arrived after a whole minute, handle shell
				// arguments instead.
				main();
			}, 60000);
		}
		data = '';
		stdin.on('data', function(chunk) {
			clearTimeout(timeout);
			data += chunk;
		});
		stdin.on('end', function() {
			strings.push(data.trim());
			main();
		});
		stdin.resume();
	}

}());
