/* global process */
/* global require */
'use strict';
var express = require('express');
var app = express();
var fs = require('fs');
var host = 'http://bas.admin.workmule.dk';
var request = require('request');
var chalk = require('chalk');
var stdin = process.stdin;
var stdout = process.stdout;
var config = JSON.parse(fs.readFileSync('serverConfig.js', 'utf8'));

var b_started = false;
var b_server = false;
var b_menu = false;
var n_step = 0;
var a_sites = Object.keys(config.sites);

var hives = [
	"system",
	".aspx"
];

var localHives = {
	"/ice-cap": "../",
	"/admin": "../admin"
};

function bootMenu() {
	console.log('\u001b[2J\u001b[0;0H');
	console.log('**************************');
	console.log('*                        *');
	console.log('*    Server boot menu    *');
	console.log('*                        *');
	console.log('*                        *');
	console.log('**************************');
	console.log('');
	console.log('1 Reset:');
	console.log('2 Server:');
	console.log('3 Quit:');
	stdout.write('Option: ');
}

function printMenu (a_options) {

	var index = 1;
	var n_count = 0;
	var s_print = "";

	a_options = a_options || a_sites;

	a_options.forEach(function(s_value) {
		s_print = s_print + index + ' - ' + s_value + ' ' + "\t";
		if (n_count == 2) {
			console.log(s_print);
			s_print = "";
		}
		n_count++;
		if (n_count > 2) {
			n_count = 0;
		}
		index++;
	});

	if (n_count) {
		console.log(s_print);
	}
	console.log('0 - Back');
	stdout.write('Option: ');
}

function init(host) {

	app.use(express.static('.', {
		maxAge: 0
	}));

	Object.keys(localHives).forEach(function(value) {
		var path = localHives[value];
		app.use(value, express.static(path, {
			maxAge: 0
		}));
	});

	hives.forEach(function (hive) {
		var reg = new RegExp('(?:/*)' + hive + '(?:/*)(.*)');

		app.get(reg, function (req, res) {
			console.log(chalk.yellow(hive + ' :get ' + req.originalUrl));
			var s_url = req.originalUrl ? host + req.originalUrl : host;
			req.pipe(request({
				url: s_url,
				form: req.body
			}, function(err, response, body) {
				if (err) {
					console.log(err, response, body);
				}
			})).pipe(res);
		});
		app.post(reg, function (req, res) {
			console.log(chalk.green(hive + ' :post ' + req.originalUrl));
			var s_url = req.originalUrl ? host + req.originalUrl : host;
			req.pipe(request({
				url: s_url,
				form: req.body
			}, function(err, httpResponse, body) {
				if (err) {
					console.log("POST:ERR - " + err);
				}
			})).pipe(res);
		});
	});

	app.all('*', function (req, res) {
		res.status(404).send('fail');
	});

	app.on("error", function(err) {
		console.log("request: " - err);
	});
}

function startServer(s_host, n_port) {
	app.listen(n_port);
	console.log('Running at http://localhost:' + n_port + "/");
}

function run(o_project) {
	init(o_project.host);
	startServer(o_project.host, o_project.port);
};

function getProject(n_project, a_options) {

	var n_port = 0;
	var a_names = [];

	a_options = a_options || a_sites;

	a_options.forEach(function(value) {
		a_names.push(value);
	});

	var o_project = config.sites[a_names[n_project - 1]];
	var s_name = a_names[n_project - 1];

	var o_return = {
		name: s_name,
		host: o_project.path,
		port: o_project.port
	};

	return o_return;
};

function f_start (n_input) {

	var b_start = false;

	if (n_input) {
		if (isNaN(n_input)) {
			console.log('Invalid option');
			console.log('Only use intergers..');
			stdout.write('Option: ');
		}
		else {
			switch (n_input) {
				case 1:
					console.log('Reset done');
					stdout.write('Option: ');
					a_sites = Object.keys(config.sites);
					break;
				case 2:
					b_start = true;
					break;
				case 3:
					process.exit();
					break;
				default:
					console.log('Invalid option');
					stdout.write('Option: ');
					break;
			}
		}
	}
	else {
		console.log('Invalid option');
		stdout.write('Option: ');
	}
	return b_start;
};

function f_server (n_input, a_options) {

	a_options = a_options || a_sites;

	if (a_options.length == 1) {
		b_started = true;
		b_menu = true;
		b_server = true;
		var s_name = a_result[0];
		var o_config = config.sites[s_name];
		var o_project = {
			name: s_name,
			host: o_config.path,
			port: o_config.port
		};
		console.log('Option chosen: ' + o_project.name + '');
		run(o_project);
		return;
	}

	if (!b_menu) {
		b_menu = true;
		printMenu(a_options);
	}
	else {
		var b_invalid = false;

		if (n_input > a_options.length) {
			console.log('Invalid option');
			stdout.write('Option: ');
		}
		else {
			switch (n_input) {
				case 0:
					b_started = false;
					b_menu = false;
					bootMenu();
					break;
				default:
					var o_project = getProject(n_input, a_options);
					if (o_project.port === 0) {
						console.log('Invalid option');
						stdout.write('Option: ');
					}
					else {
						console.log('Option chosen: ' + o_project.name + '');
						run(o_project);
					}
					b_server = true;
					break;
			}
		}
	}
};

stdin.resume();
stdin.setEncoding('utf8');

stdin.on("data", function(data) {

	if (!b_server) {
		var n_input = Number(data);

		if (!b_started) {
			b_started = f_start(n_input);
			if (b_started) {
				f_server(n_input);
			}
		}
		else {
			if (!isNaN(n_input)) {
				f_server(n_input, a_sites);
			}
			else {
				console.log('Invalid option');
				console.log('Only use intergers..');
			}
		}
	}
});

var i_args = process.argv.slice(2);

if (i_args.length > 0) {
	var s_name = i_args[0];
	var a_result = [];

	a_sites.forEach(function(s_site) {
		if (s_site.toLowerCase().indexOf(s_name.toLowerCase()) > -1) {
			a_result.push(s_site);
		}
	});

	if (a_result.length > 0) {
		a_sites = a_result;
		b_started = true;
		f_server(null, a_result);
	}
	else {
		bootMenu();
	}
}
else {
	bootMenu();
}

