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

	var fs = require('fs');
	var he = require('../he.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(
				'he v%s - http://mths.be/he',
				he.version
			);
			log([
				'\nUsage:\n',
				'\the [--escape] string',
				'\the [--encode] [--use-named-refs] [--everything] string',
				'\the [--decode] [--attribute] [--strict] string',
				'\the [-v | --version]',
				'\the [-h | --help]',
				'\nExamples:\n',
				'\the --escape \\<img\\ src\\=\\\'x\\\'\\ onerror\\=\\"prompt\\(1\\)\\"\\>',
				'\techo \'&copy; &#x1D306;\' | he --decode'
			].join('\n'));
			return process.exit(1);
		}

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

		strings.forEach(function(string) {
			// Process options
			if (string == '--escape') {
				action = 'escape';
				return;
			}
			if (string == '--encode') {
				action = 'encode';
				return;
			}
			if (string == '--use-named-refs') {
				action = 'encode';
				options.useNamedReferences = true;
				return;
			}
			if (string == '--everything') {
				action = 'encode';
				options.encodeEverything = true;
				return;
			}
			if (string == '--decode') {
				action = 'decode';
				return;
			}
			if (string == '--attribute') {
				action = 'decode';
				options.isAttributeValue = true;
				return;
			}
			if (string == '--strict') {
				action = 'decode';
				options.strict = true;
				return;
			}
			// Process string(s)
			var result;
			if (!action) {
				log('Error: he requires at least one option and a string argument.');
				log('Try `he --help` for more information.');
				return process.exit(1);
			}
			try {
				result = he[action](string, options);
				log(result);
				count++;
			} catch(error) {
				log(error.message + '\n');
				log('Error: failed to %s.', action);
				log('If you think this is a bug in he, please report it:');
				log('https://github.com/mathiasbynens/he/issues/new');
				log(
					'\nStack trace using he@%s:\n',
					he.version
				);
				log(error.stack);
				return process.exit(1);
			}
		});
		if (!count) {
			log('Error: he requires a string argument.');
			log('Try `he --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();
	}

}());
