var express = require('express');
/*var session = require('express-session');*/
var net     = require('net');
var crypto  = require('crypto');

var jade = require('jade');

var router = express.Router();

var jsonsrv = require('../lib/jsonsrv');
var pcalutils = require('../lib/pcalutils');

router.get('/:pcalview/picker', function(req, res, next) {
	var d = new Date(Date.now());
	var messages = [];
	if(req.query.start)
	{
		var matches = /^(\d{4})-(\d{2})-(\d{2})$/.exec(req.query.start);
		if(matches)
		{
			var start = Date.parse(req.query.start);
			if( ! isNaN(start))
				d = new Date(start);
			else
				messages.push({type: "danger", title: "Eingabefehler:", message: "Das von Ihnen angegeben Startdatum ('" + req.query.start + "') konnte nicht interpretiert werden! Es wird auf 'heute' ausgewichen." });
		}
		else
			messages.push({type: "danger", title: "Eingabefehler:", message: "Das von Ihnen angegeben Startdatum ('" + req.query.start + "') entspricht nicht dem Format 'yyyy-mm-dd'! Es wird auf 'heute' ausgewichen." });
	}

	res.render("datepicker", { date: d.toISOString().slice(0, 10), pcalview: req.params.pcalview, messages: messages });
});

router.get("/:pcalview/:date/select_punits_for_view", function(req, res, next) {
	var data =
		{
			"request"		: "get_pastoralunits_for_viewselection",
			"sessionuuid"   : req.session.sessionuuid,
		};

	jsonsrv.do_jsonsrv2(data,
		function(result) {
			if(result.result === "OK" )
			{
				res.render('select_punits_for_view', { u : req.params.pcalview, d : req.params.date, pastoralunits : result.pastoralunits, exclude_from_view : result.exclude_from_view } );
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});
/*
do_day = function(req, res, next, date) {
	var data = {
			"request"		: "get_parishday",
			"format"		: "day",
 			"date"			: date,
			"sessionuuid"   : req.session.sessionuuid
		};

	jsonsrv.do_jsonsrv2(data,
		function(result) {
			if(result.result === "OK" || result.result === "OK_invalid_date") {
				var params = pcalutils.do_day_renderparams_from_result(result, req.session);

				var can_go_back = true;
				if(req.query.back) {
					if(req.query.back == "false")
						params.can_go_back = false;
					else
						params.can_go_back = true;
				}
				res.render('index', params);
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
}
*/
do_timeline = function(req, res, next, date, viewformat, event) {
	var data = {
			"request"		: "get_parishday",
			"format"		: viewformat,
 			"date"			: date,
			"sessionuuid"   : req.session.sessionuuid
		};

	jsonsrv.do_jsonsrv2(data,
		function(result) {
			if(result.result === "OK" || result.result === "OK_invalid_date") {
				var params = pcalutils.do_day_renderparams_from_result(result, req.session);
				params.event = event;
				params.viewformat = viewformat;
				if(req.query.scrollto)
					params.scrollto = req.query.scrollto;
				else
					params.scrollto = "";

				var can_go_back = true;
				if(req.query.back) {
					if(req.query.back == "false")
						params.can_go_back = false;
					else
						params.can_go_back = true;
				}
				res.render('day', params);
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
}

do_week = function(req, res, next, date) {
	var data = 	{
			"request"		: "get_parishweek",
			"date"			: date,
			"sessionuuid"   : req.session.sessionuuid
		};

	jsonsrv.do_jsonsrv2(data,
		function(result) {
			if(result.result === "OK" || result.result === "OK_invalid_date") {
				var params = pcalutils.do_week_renderparams_from_result(result, req.session);

				var can_go_back = true;
				if(req.query.back) {
					if(req.query.back == "false")
						params.can_go_back = false;
					else
						params.can_go_back = true;
				}
				res.render('week', params);
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
}

/*router.get('/', function(req, res, next) {
	do_day(req, res, next, (new Date(Date.now())).toISOString().slice(0,10)); });
router.get('/day/', function(req, res, next) {
	do_day(req, res, next, (new Date(Date.now())).toISOString().slice(0,10)); });
router.get('/day/:d', function(req, res, next) {
	do_day(req, res, next, req.params.d); });*/

router.get('/', function(req, res, next) {
	do_timeline(req, res, next, (new Date(Date.now())).toISOString().slice(0,10), "day", ""); });
router.get('/day/', function(req, res, next) {
	do_timeline(req, res, next, (new Date(Date.now())).toISOString().slice(0,10), "day", ""); });
router.get('/day/:day', function(req, res, next) {
	do_timeline(req, res, next, req.params.day, "day", ""); });
router.get('/day/:day/:event', function(req, res, next) {
	do_timeline(req, res, next, req.params.day, "day", req.params.event); });

router.get('/week/', function(req, res, next) {
	do_week(req, res, next, (new Date(Date.now())).toISOString().slice(0,10)); });
router.get('/week/:d', function(req, res, next) {
	do_week(req, res, next, req.params.d); });

router.get('/timeline/', function(req, res, next) {
	do_timeline(req, res, next, (new Date(Date.now())).toISOString().slice(0,10), "timeline", ""); });
router.get('/timeline/:day', function(req, res, next) {
	do_timeline(req, res, next, req.params.day, "timeline", ""); });
router.get('/timeline/:day/:event', function(req, res, next) {
	do_timeline(req, res, next, req.params.day, "timeline", req.params.event); });

router.get('/pastoralteam/', function(req, res, next) {
	do_timeline(req, res, next, (new Date(Date.now())).toISOString().slice(0,10), "pastoralteam", ""); });
router.get('/pastoralteam/:day', function(req, res, next) {
	do_timeline(req, res, next, req.params.day, "pastoralteam", ""); });
router.get('/pastoralteam/:day/:event', function(req, res, next) {
	do_timeline(req, res, next, req.params.day, "pastoralteam", req.params.event); });

router.get('/pfarreientimeline/', function(req, res, next) {
	do_timeline(req, res, next, (new Date(Date.now())).toISOString().slice(0,10), "pfarreientimeline", ""); });
router.get('/pfarreientimeline/:day', function(req, res, next) {
	do_timeline(req, res, next, req.params.day, "pfarreientimeline", ""); });
router.get('/pfarreientimeline/:day/:event', function(req, res, next) {
	do_timeline(req, res, next, req.params.day, "pfarreientimeline", req.params.event); });


router.post("/adjust_date", function(req, res, next) {
	console.log(req.body);

	var data =
		{
			"request"		: "adjust_date",
			"sessionuuid"   : req.session.sessionuuid,
			"adjust_date"   : req.body.adjust_date
		};

	jsonsrv.do_jsonsrv2(data,
		function(result) {
			if(result.result === "OK")
				res.redirect(req.session.pcalview);
			else
				res.redirect("/login");
		},
		function(error) {
			res.redirect('/login')
		});
});

/*function do_clone_move(req, res, next, clone_or_move) {
	var data = {
			"request"		: req.params.pentrytype + "_details",
			"sessionuuid"   : req.session.sessionuuid,
			"date"			: req.params.date
		};
	data[req.params.pentrytype] = req.params.uuid;

	jsonsrv.do_jsonsrv2(data,
		function(result) {
			if(result.result === "OK") {
				var renderdata = {	pentrytype	: req.params.pentrytype,
									date 		: result.date,
									uuid 		: req.params.uuid,
									pcalview : (typeof req.query.pcalview !== 'undefined' ? req.query.pcalview : 'day'),
									sessionuuid : req.session.sessionuuid
								};

				switch(clone_or_move) {
					case "clone":
						renderdata["clone_or_move"] = "clone";
						renderdata["clone_or_move_pretty_verb"] = "geklont";
						renderdata["clone_or_move_pretty_verb2"] = "klonen";
						renderdata["clone_or_move_pretty_noun"] = "Klonen";
						break;
					case "move":
						renderdata["clone_or_move"] = "move";
						renderdata["clone_or_move_pretty_verb"] = "verschoben";
						renderdata["clone_or_move_pretty_verb2"] = "verschieben";
						renderdata["clone_or_move_pretty_noun"] = "Verschieben";
				}

				switch(req.params.pentrytype) {
					case "event":
						renderdata["pentryname"] = result.event.name;
						renderdata["pentrytype_pretty"] = "Ereignis";
						break;
					case "away":
						renderdata["pentryname"] = result.away.name;
						renderdata["pentrytype_pretty"] = "Abwesenheit";
						break;
					case "keep_in_mind":
						renderdata["pentryname"] = result.keep_in_mind.name;
						renderdata["pentrytype_pretty"] = "Zu-Beachten";
						break;
					case "todo":
						renderdata["pentryname"] = result.todo.name;
						renderdata["pentrytype_pretty"] = "Zu-Tun";
						break;
					case "vehicle_use":
						renderdata["pentryname"] = result.vehicle_use.name + " (" + result.vehicle_use.pretty.vehicle +")";
						renderdata["pentrytype_pretty"] = "Fahrzeugbenutzung";
						break;
				}
				res.render("pentrymove", renderdata);
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
}

router.get('/pentry/:date/:pentrytype/:uuid/clone', function(req, res, next) {
	do_clone_move(req, res, next, "clone")});
router.get('/pentry/:date/:pentrytype/:uuid/move', function(req, res, next) {
	do_clone_move(req, res, next, "move")});

*/
/*router.get('/email', function(req, res, next) {
	var jsondata = {
		"request"		: "get_parishdbelems_flat_email",
		"sessionuuid"	: req.session.sessionuuid
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {

			if(result.result === "OK") {

				for(idx in result.parishdb) {
					result.parishdb[idx].uid = generateUID();

					if(result.parishdb[idx].type === "group") {
						for(midx in result.parishdb[idx].members)
							result.parishdb[idx].members[midx].uid = generateUID();
					}
				}
				res.render('email', { parishdb : result.parishdb });
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error){
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});*/

router.get('/templates/:template.js', function(req, res, next) {
	res.send(jade.compileFileClient('views/'+req.params.template+".jade", {name: req.params.template+'_template', compileDebug: true}));
});

router.get('/templates/:dir/:template.js', function(req, res, next) {
	res.send(jade.compileFileClient('views/'+req.params.dir+"/"+req.params.template+".jade", {name: req.params.template+'_template', compileDebug: true}));
});

router.get('/birthdaycards/:taskuuid/download/:file', function(req, res, next) {
	var jsondata = {
		"sessionuuid"	: req.session.sessionuuid,
		"taskuuid"		: req.params.taskuuid
	};

	switch(req.params.file) {
		case "cards.pdf": jsondata.request = "get_cards"; break;
		case "envelopes.pdf": jsondata.request = "get_envelopes"; break;
		default:
			var err = new Error('Not Found');
			err.status = 404;
			res.render('error', {
				message: err.message,
				error: err
			});
			return;
	}

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {
			if(result.result === "OK") {
				res.setHeader("Content-Type", "application/pdf");
				res.send(new Buffer(result.data, 'base64'));
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error){
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});


router.get('/birthdaycards/:taskuuid', function(req, res, next) {
	var jsondata = {
		"request"		: "get_taskdata",
		"sessionuuid"	: req.session.sessionuuid,
		"taskuuid"		: req.params.taskuuid
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {
			console.log(result);
			if(result.result === "OK") {
				res.render('birthdaycards', { sessionuuid: req.session.sessionuuid, taskuuid: req.params.taskuuid, data : result });
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error){
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

router.get('/birthdaycards', function(req, res, next) {
	var jsondata = {
		sessionuuid: req.session.sessionuuid,
		request : "create_task",
		tasktype: "birthdaycards"
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {
			if(result.result === "OK")
				res.redirect('/birthdaycards/'+result.taskuuid);
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

//

router.get('/labelprinter/:taskuuid/download/:file', function(req, res, next) {
	var jsondata = {
		"sessionuuid"	: req.session.sessionuuid,
		"taskuuid"		: req.params.taskuuid
	};

	switch(req.params.file) {
		case "labels.pdf": jsondata.request = "get_labels"; break;
		case "postmen.html": jsondata.request = "get_postmen"; break;
		default:
			var err = new Error('Not Found');
			err.status = 404;
			res.render('error', {
				message: err.message,
				error: err
			});
			return;
	}

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {
			if(result.result === "OK") {
				if(req.params.file == "labels.pdf")
					res.setHeader("Content-Type", "application/pdf");
				else
					res.setHeader("Content-Type", "text/html");
				res.send(new Buffer(result.data, 'base64'));
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error){
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});


router.get('/labelprinter/:taskuuid', function(req, res, next) {
	var jsondata = {
		"request"		: "get_taskdata",
		"sessionuuid"	: req.session.sessionuuid,
		"taskuuid"		: req.params.taskuuid
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {
			console.log(result);
			if(result.result === "OK") {
				res.render('labelprinter', { sessionuuid: req.session.sessionuuid, taskuuid: req.params.taskuuid, data : result });
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error){
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

router.get('/labelprinter', function(req, res, next) {
	var jsondata = {
		sessionuuid: req.session.sessionuuid,
		request : "create_task",
		tasktype: "labelprinter"
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {
			if(result.result === "OK")
				res.redirect('/labelprinter/'+result.taskuuid);
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});


//

router.get('/patenurkunde/:taskuuid', function(req, res, next) {
	var jsondata = {
		"request"		: "get_taskdata",
		"sessionuuid"	: req.session.sessionuuid,
		"taskuuid"		: req.params.taskuuid
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {
			console.log(result);
			if(result.result === "OK") {
				console.log(result);
				res.render('patenurkunde', { sessionuuid: req.session.sessionuuid, taskuuid: req.params.taskuuid, data : result });
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error){
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

router.get('/patenurkunde', function(req, res, next) {
	var jsondata = {
		sessionuuid: req.session.sessionuuid,
		request : "create_task",
		tasktype: "patenurkunde"
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {
			if(result.result === "OK")
				res.redirect('/patenurkunde/'+result.taskuuid);
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

router.get('/patenurkunde/:taskuuid/download/:file', function(req, res, next) {
	var jsondata = {
		"sessionuuid"	: req.session.sessionuuid,
		"taskuuid"		: req.params.taskuuid,
		"request"		: "get_file",
		"filename"		: req.params.file
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {
			if(result.result === "OK") {
				if(req.params.file.endsWith(".html"))
					res.setHeader("Content-Type", "text/html");
				else
					res.setHeader("Content-Type", "application/pdf");
				res.send(new Buffer(result.data, 'base64'));
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error){
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});


//

router.get('/email/:taskuuid', function(req, res, next) {
	var jsondata = {
		"request"		: "get_parishdbelems_flat_email",
		"sessionuuid"	: req.session.sessionuuid
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {

			if(result.result === "OK") {

				for(idx in result.parishdb) {
					result.parishdb[idx].uid = generateUID();

					if(result.parishdb[idx].type === "group") {
						for(midx in result.parishdb[idx].members)
							result.parishdb[idx].members[midx].uid = generateUID();
					}
				}
				res.render('email', { sessionuuid: req.session.sessionuuid, taskuuid: req.params.taskuuid, parishdb : result.parishdb });
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error){
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

router.get('/email', function(req, res, next) {
	var jsondata = {
		sessionuuid: req.session.sessionuuid,
		request : "create_task",
		tasktype: "email"
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {
			if(result.result === "OK")
				res.redirect('/email/'+result.taskuuid);
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

router.get('/volunteerslist/:taskuuid', function(req, res, next) {
	var jsondata = {
		"request"		: "init_task",
		"sessionuuid"	: req.session.sessionuuid,
		"taskuuid"		: req.params.taskuuid
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {

			console.log(result.parishes);

			if(result.result === "OK") {
				res.render('volunteerslist', { sessionuuid: req.session.sessionuuid, taskuuid: req.params.taskuuid, sortorder: result.sortorder, parishes : result.parishes });
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error){
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

router.get('/volunteerslist', function(req, res, next) {
	var jsondata = {
		sessionuuid: req.session.sessionuuid,
		request : "create_task",
		tasktype: "volunteerslist"
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {
			if(result.result === "OK")
				res.redirect('/volunteerslist/'+result.taskuuid);
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

router.get('/volunteerslist/:taskuuid/download/letters.pdf', function(req, res, next) {
	var jsondata = {
		"sessionuuid"	: req.session.sessionuuid,
		"taskuuid"		: req.params.taskuuid,
		"request"		: "get_letters"
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {
			if(result.result === "OK") {
				res.setHeader("Content-Type", "application/pdf");
				res.send(new Buffer(result.data, 'base64'));
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error){
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});


//

router.get('/pcalimport/:taskuuid', function(req, res, next) {
	var jsondata = {
		"request"		: "init_task",
		"sessionuuid"	: req.session.sessionuuid,
		"taskuuid"		: req.params.taskuuid
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {

			console.log(result.parishes);

			if(result.result === "OK") {
				res.render('pcalimport', { sessionuuid: req.session.sessionuuid, taskuuid: req.params.taskuuid });
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error){
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

router.get('/pcalimport', function(req, res, next) {
	var jsondata = {
		sessionuuid: req.session.sessionuuid,
		request : "create_task",
		tasktype: "pcalimport"
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {
			if(result.result === "OK")
				res.redirect('/pcalimport/'+result.taskuuid);
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});


//

/*router.get('/sockettest/:taskuuid', function(req, res, next) {
	res.render('sockettest', { sessionuuid: req.session.sessionuuid, taskuuid: req.params.taskuuid});
});

router.get('/sockettest', function(req, res, next) {
	var jsondata = {
		sessionuuid: req.session.sessionuuid,
		request : "create_task",
		tasktype: "email"
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {
			if(result.result === "OK")
				res.redirect('/sockettest/'+result.taskuuid);
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});*/
/*
router.post("/pentry/:date/:pentrytype/:uuid/:clone_or_move", function(req, res, next) {
	console.log(req.body);

	var data = {
		"request"	: "pentry_clone_move",
		"sessionuuid"   : req.session.sessionuuid,
		"type"		: req.params.clone_or_move,
		"date"		: req.params.date,
		"pentrytype": req.params.pentrytype,
		"uuid"		: req.params.uuid,
		"new_date"	: req.body.new_date
	}

	jsonsrv.do_jsonsrv2(data,
		function(result) {
			if(result.result === "OK") {
				req.session.messages = result.messages.concat(req.session.messages);
				switch(req.body.pcalview) {
					case 'timeline': {
						res.redirect('/timeline/' + req.params.date);
						break;
					}
					default:
						res.redirect("/day/" + req.params.date + "?back=false");
				}

			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);

		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});*/

router.get("/parishdb", function(req, res, next) {
	var jsondata = {
		sessionuuid: req.session.sessionuuid,
		request : "get_parishdbelems_tree"
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {
			console.log(result);

			if(result.result === "OK")
				res.render("parishdb", { "parishdb": result.parishdb, "sessionuuid" : req.session.sessionuuid });
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

router.post("/select_punits_for_view", function(req, res, next) {
	console.log(req.body);

	var data =
		{
			"request"		: "exclude_pastoralunits_from_view",
			"sessionuuid"   : req.session.sessionuuid,
			"exclude_from_view" : req.body.exclude_from_view.split(',')
		};

	jsonsrv.do_jsonsrv2(data,
		function(result) {
			if(result.result === "OK")
			{
				res.redirect(req.body.u + "/" + req.body.d);
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error){
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

router.get('/about', function(req, res) {
	res.render('about');
});

router.get('/parishcalA4week/:basedate', function(req, res, next) {
	var jsondata = {
		"sessionuuid"	: req.session.sessionuuid,
		"request"		: "get_parishcalA4week",
		"date"			: req.params.basedate
	};

	jsonsrv.do_jsonsrv2(jsondata,
		function(result) {
			if(result.result === "OK") {
				res.setHeader("Content-Type", "application/pdf");
				res.send(new Buffer(result.data, 'base64'));
			}
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error){
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});


router.get('/login', function(req, res) {
	res.render('login');
});


hash = function(pwd, salt)
{
	var len = 32;
	var iterations = 12000;
	var h = crypto.pbkdf2Sync(pwd, salt, iterations, len, 'sha512');
	var s = h.toString('hex')

	return (new Buffer(s).toString('base64'));
}

router.post('/login', function(req, res){

	var email = req.body.ID1;
	var data =
		{
			"request": "auth",
			"id1"    : email,
			"id2"    : hash(req.body.ID2, email),
			"id3"    : hash(req.body.ID3, email)
		};

	jsonsrv.do_jsonsrv2(data,
		function(result) {
			console.log(result.authresult);
			if(result.authresult === "OK")
			{
				console.log(result.username);
				console.log(result.sessionuuid);
				console.log(result.pfis_login_c);

				var maxAge = 60*60*24*7*1000;
				console.log("maxAge: ", maxAge);

				res.cookie("pfis_login_c", result.pfis_login_c, {maxAge: maxAge, httpOnly: true });

				req.session.regenerate(function(){
					req.session.user = result.username;
					req.session.sessionuuid  = result.sessionuuid;
					req.session.cache = { days : {} };
					req.session.messages = [];
					res.redirect("/");
				});
			}
			else
				res.redirect("http://www.erzbistum-bamberg.de");
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

router.get('/logout', function(req, res){
	// destroy the user's session to log them out
	// will be re-created next request
	req.session.destroy(function(){
		res.clearCookie("pfis_login_c");
		res.redirect('/login');
	});

});

module.exports = router;
