var net = require('net');

var pfisjsonhost = "127.0.0.1";

console.log(process.env["NODE_ENV"])
if (process.env["NODE_ENV"] === 'production') {
	//pfisjsonhost = "127.0.0.1";
	pfisjsonhost = "10.0.0.4";
}
console.log(pfisjsonhost);

function byteCount(s) {
	return encodeURI(s).split(/%(?:u[0-9A-F]{2})?[0-9A-F]{2}|./).length - 1;
}

function format_json_for_send(data) {
	var str = JSON.stringify(data);
	//console.log(str);

	var n = str.length;
	//console.log("str.length: ", n);
	n = byteCount(str);
	//console.log("bytes     : ", n);
	/*var n_hex = n.toString(16);
	var n_str = "" + n_hex;

	var n_msg = ('00000000'+n_str).substring(n_str.length);

	console.log(n_msg + str);

	return n_msg + str;*/

	return str + "__END_OF_JSON__";
}

exports.format_json_for_send = format_json_for_send;

exports.do_jsonsrv = function(req, res, data, result_func, error_func) {
	var client = new net.Socket();
	var input = '';

	client.connect(1337, pfisjsonhost, function() {
		/*client.setNoDelay(true);*/
		console.log('Connected');

		client.write(format_json_for_send(data));
	});

	client.on('data', function(data) {
		input += data;
	});

	client.on('end', function() {
		var result = JSON.parse(input);

		result_func(req, res, result);

		client.destroy(); // kill client after server's response
	});

	client.on('error', function(err) {
		console.log(err);
		error_func(req, res, err);
	});

	client.on('close', function() {
		console.log('Connection closed');
	});
}

function buffer_to_json(input, result_func, error_func) {
	try {
		var result = JSON.parse(input);
		result_func(result);
	}catch(err) {
		console.log("--------------------------------------");
		console.log("--------------------------------------");
		console.log("ERROR RETRIEVING DATA VOM PFISJSONSRV!");
		console.log("--------------------------------------");
		console.log(err);
		console.log("--------------------------------------");
		console.log("INPUT --------------------------------");
		console.log(input);
		console.log("--------------------------------------");
		error_func(err);
	}
}

exports.do_jsonsrv2 = function(data, result_func, error_func) {

	var client = new net.Socket();
	var input = '';

	client.connect(1337, pfisjsonhost, function() {
		/*client.setNoDelay(true);*/
		console.log('Connected');

		client.write(format_json_for_send(data));
	});

	client.on('data', function(data) {
		input += data;
	});

	client.on('end', function() {
		//console.log("input: ", input);
		buffer_to_json(input, result_func, error_func);

		client.destroy(); // kill client after server's response
	});

	client.on('error', function(err) {
		error_func(err);
	});

	client.on('close', function() {
		console.log('Connection closed');
	});
}

exports.do_jsonsrv_steppedanswer = function(data, step_func, result_func, error_func) {
	var client = new net.Socket();
	var input = '';

	client.connect(1337, pfisjsonhost, function() {
		/*client.setNoDelay(true);*/
		console.log('Connected');

		client.write(format_json_for_send(data));
	});

	client.on('data', function(data) {
		console.log('DATA RECEIVED: ', "" + data);
		console.log('DATE END');

		var stepidx = data.indexOf("__STEP__");
		if(stepidx === -1) {
			input += data;
			return;
		}

		input += data.slice(0, stepidx);

		do{
			console.log("STEP COMPLETE: ", input);
			console.log("STEP END______");
			buffer_to_json(input, step_func, error_func);

			// BEGIN NEXT STEP:
			console.log('BEGINN NEXT STEP');
			var oldstepindex = stepidx + 8;
			stepidx = data.indexOf("__STEP__", oldstepindex);
			if(stepidx === -1)
				stepidx = data.length;
			input = data.slice(oldstepindex, stepidx);
			console.log("NEW STEP START: ", ""+ input);
			console.log("NEW STEP END");
		}while(stepidx < data.length)
	});

	client.on('end', function() {
		//console.log("input: ", input);
		buffer_to_json(input, result_func, error_func);

		client.destroy(); // kill client after server's response
	});

	client.on('error', function(err) {
		error_func(err);
	});

	client.on('close', function() {
		console.log('Connection closed');
	});
}


exports.handle_jsonconnectionerror = function(req, res, err) {
	console.log("-----------------------------");
	console.log("-----------------------------");
	console.log("ERROR CONNECTING PFISJSONSRV!");
	console.log("-----------------------------");
	console.log(err);
	console.log("-----------------------------");

	// Connection-Errors are hard errors, so we display an hard error
	res.status(err.status || 500);
	res.render('error', {
		message: err.message,
		error: err
	});
}

exports.handle_common_jsonsrverrors = function (req, res, result) {
	if(result.result === "ERROR_invalid_session") {

		req.session.destroy();

		res.render("errorview", { messages : result.messages });

		return;
	}

	if(result.result == "ERROR_download_file_not_found")
	{
		var err = new Error('Not Found');
		err.status = 404;
		res.render('error', {
			message: err.message,
			error: err
		});
		return;
	}

	req.session.messages = result.messages.concat(req.session.messages);

	if(req.session.messages.length === 0)
		req.session.messages.push({type: "danger", title: "Systemfehler", message: "Es wurde ein Fehler in der Verarbeitung festgestellt, aber keine Fehlermeldung erstellt."});

	if(result.result === "ERROR_could_not_create_task")
	{
		res.render("errorview", { messages : result.messages });

		return;
	}

	if(result.result === "ERROR_could_not_init_task")
	{
		res.render("errorview", { messages : result.messages });

		return;
	}

	req.session.messages.push({type: "info", title: "Umleitung erfolgt", message: "Aufgrund vorstehender Fehler in der Verarbeitung Ihrer Anfrage wurde Sie auf die Startseite umgeleiet."});

	var date = "";
	if(req.params.date)
		date = "/"+req.params.date;
	else if(req.params.day)
		date = "/"+req.params.day;

	res.redirect('/day' + date + "?back=false");
}
