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

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

function event_from_session(req) {
console.log(req.params);
	console.log(req.session.cache.days);
	console.log(req.session.cache.days[req.params.day]);
	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;
	}
	if(typeof req.session.cache.days[req.params.day].events[req.params.event].thereafter[req.params.tevent] === 'undefined') {
		console.log('event_from_session: thereafter ', req.params.thereafter, ' of event ', req.params.event, ' not defined in day ', req.params.day, '!');
		return null;
	}
	return req.session.cache.days[req.params.day].events[req.params.event].thereafter[req.params.tevent];
}

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 end_tevent_editing(day, event, tevent) {
	console.log(Object.keys(event.thereafter).length);

	console.log("deleteing thereafter: ", tevent.uuid);

	delete event.thereafter[tevent.uuid];

	console.log(Object.keys(event.thereafter).length);

	eventutils.delete_event_if_nothing_is_edited(day, event);
}

router.get('/:day/:event/:tevent/cancel', function(req, res, next) {
	console.log('NOW REDIRECT');

	end_tevent_editing( req.session.cache.days[req.params.day],
		req.session.cache.days[req.params.day].events[req.params.event],
		req.session.cache.days[req.params.day].events[req.params.event].thereafter[req.params.tevent]);


	switch(req.query.pcalview) {
		case 'timeline': {
			res.redirect('/timeline/'+req.params.day+'/'+req.params.event);
			break;
		}
		default: {
			res.redirect('/day/'+req.params.day+'/'+req.params.event);
		}
	}
});

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

	console.log(req.body);

	var event = event_from_session(req);
	if(event_from_session_is_invalid(req, res, event))
		return;

    console.log(event);

	event.name = req.body.edit_name;
	event.name_secondary = req.body.edit_name_secondary;
	event.visibility = req.body.combo_type;
	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_thereafter",
		"sessionuuid" : req.session.sessionuuid,
		"date"		  : req.params.day,
		"event"		  : req.params.event,
		"thereafter"  : req.params.tevent,
		"event_data"  : event
	};

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

				switch(req.body.pcalview) {
					case 'timeline': {
						res.redirect('/timeline/' + req.params.day + '/'+ req.params.event);
					}
					default : {
						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_tevent_edit(req, res) {
	var event_href = "/tevent/" + req.params.day + "/" + req.params.event + "/" + req.params.tevent;

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

	res.render("event_edit_container", { 	date: req.session.cache.days[req.params.day].date,
											pentrytype : "tevent",
											pentrytype_pretty: the_event.parent_pretty,
											parent_event : req.session.cache.days[req.params.day].events[req.params.event],
											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_tevent_edit');
}

router.get('/:day/:event/:tevent/edit', function(req, res, next) {
	if( req.session.cache.days[req.params.day] ) {
		if( req.session.cache.days[req.params.day].events[req.params.event] ) {
			if( req.session.cache.days[req.params.day].events[req.params.event].thereafter[req.params.tevent] ) {
				render_tevent_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("created new day:");
		console.log(req.session.cache.days[req.params.day]);
	}

	if(! req.session.cache.days[req.params.day].events[req.params.event] )
	{
		// the parent-event is not loaded for editing, so create an empty object
		req.session.cache.days[req.params.day].events[req.params.event] = { in_editing: false, uuid : req.params.event, thereafter: {}};
	}

	// for the thereafter-event to be edited or created, we always use 'event_details' als request!
	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.cache.days[req.params.day].date = result.date;
				req.session.date = result.date;

				if(req.params.tevent === "new") {

					var uuid = "new_" + generateUID();
					var new_event = eventutils.create_empty_thereafter();
					new_event.uuid = uuid;
					new_event.parent_start = result.event.start;
					req.session.cache.days[req.params.day].events[req.params.event].thereafter[uuid] = new_event;

					req.session.cache.days[req.params.day].events[req.params.event].thereafter[uuid].parent_start = result.event.start;
					req.session.cache.days[req.params.day].events[req.params.event].thereafter[uuid].parent_pretty = "Folgeereignis von \"" + result.event.name + "\"";
					if(result.event.pretty.time.length > 0)
						req.session.cache.days[req.params.day].events[req.params.event].thereafter[uuid].parent_pretty += " (" + result.event.pretty.time + ")";

					console.log(new_event);

					var pcalview = "";
					if(req.query.pcalview)
						pcalview = '?pcalview='+req.query.pcalview;
					res.redirect('/tevent/'+req.params.day+'/'+ req.params.event +'/'+uuid+'/edit' + pcalview);
				}
				else {
					req.session.cache.days[req.params.day].events[req.params.event].thereafter[req.params.tevent] = {};

					var found = false;
					// now searching the thereafter
					for(idx in result.event.thereafter) {
						if(result.event.thereafter[idx].uuid === req.params.tevent) {
								req.session.cache.days[req.params.day].events[req.params.event].thereafter[req.params.tevent] =
									result.event.thereafter[idx];
							found = true;
							break;
						}
					}

					req.session.cache.days[req.params.day].events[req.params.event].thereafter[req.params.tevent].parent_start = result.event.start;
					req.session.cache.days[req.params.day].events[req.params.event].thereafter[req.params.tevent].parent_pretty = "Folgeereignis von \"" + result.event.name + "\"";
					if(result.event.pretty.time.length > 0)
						req.session.cache.days[req.params.day].events[req.params.event].thereafter[req.params.tevent].parent_pretty += " (" + result.event.pretty.time + ")";

					console.log("NOW ADDING UIDs");
					eventutils.add_uids_to_event(req.session.cache.days[req.params.day].events[req.params.event].thereafter[req.params.tevent]);
					console.log("END ADDING UIDs");

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

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

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

	jsonsrv.do_jsonsrv(req, res, data,
		function(req, res, result) {
			if(result.result === "OK")
				res.redirect( "/day");
			else
				res.redirect("/login");
		},
		redirect_to_login);
});*/

module.exports = router;
