var express = require('express');
var router = express.Router();

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

router.get('/:day/:event', function(req, res, next) {
	var data =
		{
			"request"		: "event_details",
			"sessionuuid"   : req.session.sessionuuid,
		    "date"			: req.params.day,
			"event"			: req.params.event,
		};

	jsonsrv.do_jsonsrv2(data,
		function(result) {
			if(result.result === "OK")
				res.render("event_details", { date: result.date.date, event: result.event });
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req,  res, error);
		});
});

function event_from_session(req)
{
	if(typeof req.session.cache.days[req.params.day] === 'undefined')
	{
		console.log("-> day undefined");
		return null;
	}
	if(typeof req.session.cache.days[req.params.day].events[req.params.event] === 'undefined')
	{
		console.log("-> event undefined");
		return null;
	}
	return req.session.cache.days[req.params.day].events[req.params.event];
}

function event_from_session_is_invalid(req, res, ev)
{
	if(ev === null)
	{
		console.log('EVENT UNDEFINED!');
		console.log(req.params);
		res.redirect('/day');
		return true;
	}
	return false;
}

/*function delete_event_if_nothing_is_edited(day, event)
{
	if(event.in_editing)
		return;

	var can_delete = true;
	for(idx in event.thereafter)
	{
		if(event.thereafter[idx].in_editing === true)
		{
			can_delete = false;
			break;
		}
	}
	if(can_delete)
	{
		var found = false;
		var idx;
		for(idx in day.events)
		{
			console.log("DELETE_IDX", idx);
			if(day.events[idx].uuid === event.uuid)
			{
				found = true;
				break;
			}
		}

		if(found)
		{
			console.log("DELETING EVENT: ", event.uuid);
			delete day.events[event.uuid];
		}
	}
}*/

function end_event_editing(day, event) {
	event.in_editing = false;

	eventutils.delete_event_if_nothing_is_edited(day, event);
}

router.get('/:day/:event/cancel', function(req, res, next) {
	end_event_editing( 	req.session.cache.days[req.params.day],
						req.session.cache.days[req.params.day].events[req.params.event]);

	console.log('NOW REDIRECT');

	switch(req.query.pcalview) {
		case 'timeline': {
			if(req.params.event.substring(0, 4) === "new_")
				res.redirect("/timeline/" + req.params.day);
			else
				res.redirect('/timeline/' + req.params.day + '/' + req.params.event);
			break;
		}
		default: {
			if(req.params.event.substring(0, 4) === "new_")
				res.redirect("/day/" + req.params.day + "?back=false");
			else
				res.redirect('/day/' + req.params.day + '/' +req.params.event);

		}
	}

});

router.post('/:day/:event/commit', function(req, res, next) {

	var event = event_from_session(req);
	console.log("EVENT_form_session: ", event, "\n___");
	if(event_from_session_is_invalid(req, res, event))
		return;

	//event.punit = { name : req.body.punit_name, dn : req.body.punit_dn };
	event.name = req.body.edit_name;
	event.name_secondary = req.body.edit_name_secondary;
	event.visibility = req.body.combo_type;
	event.start = req.body.edit_begin;
	event.end = req.body.edit_end;
	if(event.end !== "")
		event.end_is_vague = (req.body.check_end_is_vague === "on" ? true : false);
	event.description = req.body.area_description;
 	event.annotations = req.body.area_annotations;

	console.log(event);

	var data = {
		"request"     : "commit_event",
		"sessionuuid" : req.session.sessionuuid,
		"date"		  : req.params.day,
		"event"		  : req.params.event,
		"event_data"  : event
	};

	jsonsrv.do_jsonsrv2(data,
		function(result) {
			if(result.result === "OK") {
				end_event_editing(req.session.cache.days[req.params.day], event);

				switch(req.body.pcalview) {
					case 'pfarreientimeline' : {
						if(req.params.event.substr(0,4) === "new_")
							res.redirect("/pfarreientimeline/" + req.params.day + "?scrollto=" + request.uuid);
						else
							res.redirect('/pfarreientimeline/' + req.params.day + '/' + req.params.event);
					}
					case 'pastoralteam' : {
						if(req.params.event.substr(0,4) === "new_")
							res.redirect("/pastoralteam/" + req.params.day + "?scrollto=" + request.uuid);
						else
							res.redirect('/pastoralteam/' + req.params.day + '/' + req.params.event);
					}
					case 'timeline': {
						if(req.params.event.substr(0,4) === "new_")
							res.redirect("/timeline/" + req.params.day + "?scrollto=" + request.uuid);
						else
							res.redirect('/timeline/' + req.params.day + '/' + req.params.event);
					}
					default : {
						if(req.params.event.substr(0,4) === "new_")
							res.redirect("/day/" + req.params.day + "?back=false");
						else
							res.redirect('/day/' + req.params.day + '/' + req.params.event);

					}
				}
			}
			else {
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
			}
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

generateUID = function() {
	return ("0000" + (Math.random()*Math.pow(36,4) << 0).toString(36)).slice(-4)
}

function render_event_edit(req, res) {
	var event_href = "/event/" + req.params.day + "/" + req.params.event;

	var the_event = req.session.cache.days[req.params.day].events[req.params.event];

	res.render("event_edit_container", { 	date: req.session.cache.days[req.params.day].date,
											pentrytype: "event",
											pentrytype_pretty: "Ereignis",
											pentry: the_event,
											pentry_href : event_href,
											pcalview : (typeof req.query.pcalview !== 'undefined' ? req.query.pcalview : 'day'),
											edit_type: (the_event.uuid.substr(0,4) === "new_" ? "erstellen" : "bearbeiten") });

	console.log('render_event_edit');
}

router.get('/:day/:event/edit', function(req, res, next) {
	if(typeof req.session.cache.days[req.params.day] !== 'undefined') {
		if(typeof req.session.cache.days[req.params.day].events[req.params.event] !== 'undefined') {
			if(req.session.cache.days[req.params.day].events[req.params.event].in_editing === true) {
				render_event_edit(req, res);
				return;
			}
		}
	}
	else {
		var day = {
				events: {},
				away  : {},
				keep_in_mind : {},
				todo         : {},
				vehicle_use  : {}
			};

		req.session.cache.days[req.params.day] = day;

		console.log(req.session.cache.days);

		console.log("created new day:");
		console.log(req.session.cache.days[req.params.day]);
	}

	if(req.params.event === "new") {
		var data = {
				"request"		: "get_parishday",
				"sessionuuid"   : req.session.sessionuuid,
				"date"			: req.params.day,
			};

		jsonsrv.do_jsonsrv2(data,
			function(result) {
				if(result.result === "OK")
				{
					req.session.cache.days[req.params.day].date = result.day.date;
					req.session.date = result.day.date;

					var uuid = "new_" + generateUID();
					var new_event = eventutils.create_empty_event();
					new_event.uuid = uuid;
					new_event.in_editing = true;
					new_event.thereafter = {};
					req.session.cache.days[req.params.day].events[uuid] = new_event;

					//render_event_edit(req, res );
					var pcalview = "";
					if(req.query.pcalview)
						pcalview = '?pcalview='+req.query.pcalview;
					res.redirect('/event/'+req.params.day+'/'+uuid+'/edit' + pcalview);
				}
				else
					jsonsrv.handle_common_jsonsrverrors(req, res, result);
			},
			function(error) {
				jsonsrv.handle_jsonconnectionerror(req, res, error);
			});
	}
	else
	{
		var data =
		{
			"request"		: "event_details",
			"sessionuuid"   : req.session.sessionuuid,
			"date"			: req.params.day,
			"event"			: req.params.event,
		};

		jsonsrv.do_jsonsrv2(data,
			function(result) {
				if(result.result === "OK")
				{
					req.session.date = result.date;
					req.session.cache.days[req.params.day].date = result.date;

					// the event-object might exist, if there is a thereafter of it editet in the same session (other window)
					// so we create it only, if it does not exist, so that thereafters in editing are not deleted!
					if(! req.session.cache.days[req.params.day].events[req.params.event] ) {
						console.log("creating new event-object for ", req.params.day, "/", req.params.event);
						req.session.cache.days[req.params.day].events[req.params.event] = { thereafter: {} };
					}
					else
						console.log("using existing (from thereafter!) event-object for ", req.params.day, "/", req.params.event);

					eventutils.copy_event_without_thereafter(req.session.cache.days[req.params.day].events[req.params.event], result.event)
					req.session.cache.days[req.params.day].events[req.params.event].in_editing = true;

					console.log("NOW ADDING UIDs");
					eventutils.add_uids_to_event(req.session.cache.days[req.params.day].events[req.params.event]);
					/* NOT NECCESSARY: WE DO NOT SAVE THEREAFTERS WHICH WE GOT IN THIS event_details-call!
					// they are loaded, when we edit them (see tevents.js!)
					thereafter = req.session.cache.days[req.params.day].events[req.params.event].thereafter;
					for(idx in thereafter)
					{
						add_uids_to_event(thereafter[idx]);
						thereafter[idx].in_editing = false;
					}*/
					console.log("END ADDING UIDs");

					render_event_edit(req, res);
				}
				else
					jsonsrv.handle_common_jsonsrverrors(req, res, result);
			},
			function(error) {
				jsonsrv.handle_jsonconnectionerror(req, res, error);
			});
	}
});


/*router.get('/:day/:event/clone', function(req, res, next) {
	var data =
		{
			"request"		: "event_details",
			"sessionuuid"   : req.session.sessionuuid,
		    "date"			: req.params.day,
			"event"			: req.params.event,
		};

	jsonsrv.do_jsonsrv(req, res, data,
		function(req, res, result) {
			if(result.result === "OK")
				res.render("pentrymove", {	pentrytype: "event",
											date 		: result.date.date,
											uuid 		: result.event.uuid,
											clone_or_move: "clone",
											clone_or_move_pretty_verb: "geklont",
											clone_or_move_pretty_noun: "Klonen",
											pcalview : (typeof req.query.pcalview !== 'undefined' ? req.query.pcalview : 'day'),
											pentryname: "das Ereignis \"" + result.event.name +"\"",
										});
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

router.get('/:day/:event/move', function(req, res, next) {
	var data =
		{
			"request"		: "event_details",
			"sessionuuid"   : req.session.sessionuuid,
			"date"			: req.params.day,
			"event"			: req.params.event,
		};

	jsonsrv.do_jsonsrv2(data,
		function(result) {
			if(result.result === "OK")
				res.render("pentrymove", {	pentrytype: "event",
											date 		: result.date.date,
											uuid 		: result.event.uuid,
											clone_or_move: "move",
											clone_or_move_pretty_verb: "verschoben",
											clone_or_move_pretty_noun: "Verschieben",
											pcalview : (typeof req.query.pcalview !== 'undefined' ? req.query.pcalview : 'day'),
											pentryname: "das Ereignis \"" + result.event.name +"\"",
										});
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});*/

router.post('/:day/:event/delete', function(req, res,  next) {
	console.log(req.body);

	var data = {
			"request"		: "delete_event",
			"sessionuuid"   : req.session.sessionuuid,
			"date"			: req.params.day,
			"event"			: req.params.event,
		};

	jsonsrv.do_jsonsrv(req, res, data,
		function(req, res, result) {
			if(result.result === "OK")
				res.redirect("/day/" + req.params.day + "?back=false");
			else
				jsonsrv.handle_common_jsonsrverrors(req, res, result);
		},
		function(error) {
			jsonsrv.handle_jsonconnectionerror(req, res, error);
		});
});

module.exports = router;

/*

router.get('/:day/:event/select_pastoralunit', function(req, res, next) {
	var data =
		{
			"request"		: "get_all_pastoralunits",
			"sessionuuid"   : req.session.sessionuuid
		};

	jsonsrv.do_jsonsrv2(data,
		function(result) {
			if(result.result === "OK")
			{
				var event = event_from_session(req);

				res.render("pastoralunitselector", {
														actual_punit_dn : event.punit.dn,
														actual_punit_name: event.punit.name,
														pentry_edit_base: '/event/' + req.params.day + '/' + req.params.event,
														pastoralunits: result.pastoralunits
				});
			}
			else
				res.redirect("/login");
		},
		redirect_to_login);
});

router.post('/:day/:event/pastoralunit_selected', function(req, res, next) {
	var event = event_from_session(req);
	event.punit.dn   = req.body.actual_punit_dn;
	event.punit.name = req.body.actual_punit_name;

	console.log(event);

	res.redirect('/event/' + req.params.day + '/' + req.params.event + "/edit");
});

router.get('/:day/:event/add_predefined_location', function(req, res, next) {
	var data =
		{
			"request"	: "get_all_predefined_locations",
			"sessionuuid": req.session.sessionuuid,
			"omitt"		: []
		};

	for(idx in req.session.event.locations)
	{
		var loc = req.session.event.locations[idx];
		if(loc.id != "other")
			data.omitt.push(loc.id);
	}

	jsonsrv.do_jsonsrv2(data,
		function(result) {
			if(result.result === "OK")
			{
				res.render("locationselector", {
											pentry_edit_base: '/event/' + req.params.day + '/' + req.params.event,
											units: result.locations
						});
			}
			else
				res.redirect('/login');
		},
		function(error) {
			res.redirect('/login');
		});
});

router.post('/:day/:event/add_predefined_location', function(req, res, next) {

	var loc =
		{
			uid : generateUID(),
			name : req.body.actual_location_name,
			sign : req.body.actual_location_sign,
			id   : req.body.actual_location_id
		};

	var event = event_from_session(req);

	event.locations.push(loc);

	console.log(event.locations);

	res.redirect('/event/' + req.params.day + '/' + req.params.event + "/edit#locations");
});

router.get('/:day/:event/add_actor', function(req, res, next) {
	var data =
		{
			"request"		: "get_all_actors",
			"sessionuuid"	: req.session.sessionuuid,
			"omitt"			: []
		};

	var role = '';

	if(typeof req.query.role !== 'undefined')
	{
		role = req.query.role;
		console.log('ADD ACTOR FOR ROLE '+req.query.role);
	}

	var event = event_from_session(req);
	var the_involved = get_involved_from_event(event, role);

	for(a in the_involved)
	{
		var actor = the_involved[a];
		if(actor.id !== "other" && actor.id !== "dn")
			data.omitt.push(actor.id);
	}

	jsonsrv.do_jsonsrv2(data,
		function(result) {
			if(result.result === "OK")
			{
				res.render("actorselector", {
												pentry_edit_base: '/event/' + req.params.day + '/' + req.params.event,
												units: result.actors,
												for_role: role
				});
			}
			else
				res.redirect("/login");
		},
		redirect_to_login);
});

router.post('/:day/:event/add_actor', function(req, res, next) {

	var actor =
		{
			uid : generateUID(),
			name : req.body.actual_actor_name,
			id   : req.body.actual_actor_id
		};

	var event = event_from_session(req);
	var the_involved = get_involved_from_event(event, req.body.for_role);

	the_involved.push(actor);

	console.log(the_involved);

	res.redirect('/event/' + req.params.day + '/' + req.params.event + "/edit");
});

function do_add_edit_role(req, res, next, pentry_edit_base, submit_dest, role_uid)
{
	var data =
		{
			"request"		: "get_predefined_roles",
			"sessionuuid"	: req.session.sessionuuid,
		};

	jsonsrv.do_jsonsrv2(data,
		function(result) {
			if(result.result === "OK")
			{
				var event = event_from_session(req);
				var role_name = '';
				if(submit_dest == 'edit_role')
				{
					role_name = get_role_from_uid(event, role_uid).name;
				}

				var already_defined_roles = [];
				for( idx in event.involved_roles )
				{
					if(event.involved_roles[idx].name !== role_name)
						already_defined_roles.push(event.involved_roles[idx].name);
				}

				res.render("roleeditor", {
											pentry_edit_base: pentry_edit_base,
											roles : result.roles,
											submit_dest : submit_dest,
											role_name : role_name,
											role_uid : role_uid,
											already_defined_roles : already_defined_roles
				});
			}
			else
				res.redirect("/login");
		},
		redirect_to_login);
}

router.get('/:day/:event/add_role', function(req, res, next) {
	do_add_edit_role(req, res, next, '/event/' + req.params.day + '/' + req.params.event, 'add_role', '')
});

router.get('/:day/:event/edit_role/:role', function(req, res, next) {
	do_add_edit_role(req, res, next, '/event/' + req.params.day + '/' + req.params.event, 'edit_role', req.params.role)
});

router.post('/event/:day/:event/add_role', function(req, res, next) {
	var role =
		{
			uid : generateUID(),
			name : req.body.role_name,
			involved : []
		};

	var event = event_from_session(req);

	event.involved_roles.push(role);

	console.log(event);

	res.redirect('/event/' + req.params.day + '/' + req.params.event + "/edit");
});

router.post('/:day/:event/edit_role', function(req, res, next) {
	console.log(req.body);

	var event = event_from_session(req);
	get_role_from_uid(event, req.body.role_uid).name = req.body.role_name;

	console.log(event);

	res.redirect('/event/' + req.params.day + '/' + req.params.event + "/edit");
});


*/
