/*
 * Description: Interactive SSH Terminal running on nodejs
 * Author: Aaron Gong
 * Date: 2014-11-17
 * http://www.pulse.sg/posts/nodejs_ssh_terminal
 * Licence: MIT
 */
const wsize = require('window-size');
const chalk = require('chalk');
const Connection = require('ssh2'); // npm install ssh2
const conn = new Connection();

let windowSize = wsize.get();

const forwardIn = () => {
	return new Promise((resolve, reject) => {
		conn.forwardIn('127.0.0.1', 8000, function(err) {
			if (err) throw err;
			console.log('Listening for connections on server on port 8000!');
		});
	})
}

const forwardOut = () => {
	return new Promise((resolve, reject) => {
		conn.forwardOut(
			info.srcAddr,
			info.srcPort,
			info.dstAddr,
			info.dstPort,
		function(err, stream) {
			if(err) reject(err);
			else resolve(stream);
		})
	})
}

module.exports = (ops) => {
	return new Promise((resolve, reject) => {
		let gs = null;

		conn.on('error', (err) => {
			console.log(error);
			throw err;
		});

		// conn.on('*', () => console.log('conn closed'));

		conn.on('ready', function () {
			console.log(chalk.yellow('Connection :: ready!'));

			conn.shell(function (err, stream) {
				if (err) throw(err);
				else {
					// Set initial window size
					stream.setWindow(process.stdout.rows, process.stdout.columns, windowSize.height, windowSize.width);

					stream.on('close', function () {
						console.log(chalk.cyan('Connection :: closed'));
						conn.end();
					}).on('data', function (data) {
						if (!gs) gs = stream;
						// if (gs._writableState.sync == false) 
						process.stdout.write('' + data);
					}).stderr.on('data', function (data) {
						console.log('STDERR: ' + data);
						reject(data);
					});

					// Set window size on resizing
					process.stdout.on('resize', () => {
						windowSize = wsize.get();
						stream.setWindow(process.stdout.rows, process.stdout.columns, windowSize.height, windowSize.width);
					});

					resolve(true);
				}
			});

		}).connect(ops);

		// The code below is from the link below. I just sent key press to stream used by SSH instead of stdout
		// http://stackoverflow.com/questions/5006821/nodejs-how-to-read-keystrokes-from-stdin
		// 
		const stdin = process.stdin;
		stdin.setRawMode(true); // without this, we would only get streams once enter is pressed
		stdin.resume(); // resume stdin in the parent process (node app won't quit all by itself unless an error or process.exit() happens)
		stdin.setEncoding('utf8'); // i don't want binary, do you?
		stdin.on('data', function (key) { // on any data into stdin
			// if (key === '\u0003') { // ctrl-c ( end of text )
			// 	process.exit();
			// }
			if (gs) gs.write('' + key); // write the key to stdout all normal like
		});
	})
}
