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

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

function todo_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].todo[req.params.todo] === 'undefined')
	{
		console.log("-> todo undefined");
		return null;
	}
	return req.session.cache.days[req.params.day].todo[req.params.todo];
}

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

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

	pcalutils.redirect_after_editing(req, res);
});

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

	console.log(req.body);

	var todo = todo_from_session(req);
	if(todo_from_session_is_invalid(req, res, todo))
		return;

	todo.name = req.body.edit_name;
	todo.description = req.body.area_description;

	console.log(todo);

	var data = {
		"request"     : "commit_todo",
		"sessionuuid" : req.session.sessionuuid,
		"date"		  : req.params.day,
		"todo"		  : req.params.todo,
		"todo_data"   : todo
	};

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

				pcalutils.redirect_after_editing(req, res);
			}
			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_todo_edit(req, res) {
	var the_todo = req.session.cache.days[req.params.day].todo[req.params.todo];

	res.render("event_edit_container", { 	date: req.session.cache.days[req.params.day].date,
											pentrytype: "todo",
											pentrytype_pretty: "Zu-Tun",
											pentry: the_todo,
											pentry_href : "/todo/" + req.params.day + "/" + req.params.todo,
                                            pcalview : (typeof req.query.pcalview !== 'undefined' ? req.query.pcalview : 'day'),
											edit_type: (the_todo.uuid.substr(0,4) === "new_" ? "erstellen" : "bearbeiten") });

	console.log('render_todo_edit');
}

router.get('/:day/:todo/edit', function(req, res, next) {
	if(typeof req.session.cache.days[req.params.day] !== 'undefined') {
		if(typeof req.session.cache.days[req.params.day].todo[req.params.todo] !== 'undefined') {
			render_todo_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.todo === "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_todo = pcalutils.create_empty_todo(uuid);
					req.session.cache.days[req.params.day].todo[uuid] = new_todo;

					var pcalview = "";
					if(req.query.pcalview)
					    pcalview = '?pcalview='+req.query.pcalview;
					res.redirect('/todo/'+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"		: "todo_details",
			"sessionuuid"   : req.session.sessionuuid,
			"date"			: req.params.day,
			"todo"			: req.params.todo,
		};

		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;

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

					for(var idx in req.session.cache.days[req.params.day].todo[req.params.todo].involved) {
						req.session.cache.days[req.params.day].todo[req.params.todo].involved[idx].uid = generateUID();
					}

					console.log(req.session.cache.days[req.params.day].todo[req.params.todo].involved);

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

module.exports = router;
