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

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

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

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

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

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

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

	console.log(req.body);

	var vehicle_use = vehicle_use_from_session(req);
	if(vehicle_use_from_session_is_invalid(req, res, vehicle_use))
		return;

	vehicle_use.name = req.body.edit_name;
	vehicle_use.description = req.body.area_description;
	vehicle_use.vehicle_id = req.body.combo_vehicle;

	console.log(vehicle_use);

	var data = {
		"request"     : "commit_vehicle_use",
		"sessionuuid" : req.session.sessionuuid,
		"date"		  : req.params.day,
		"vehicle_use"		  : req.params.vehicle_use,
		"vehicle_use_data"   : vehicle_use
	};

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

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

function get_all_vehicles(req, res) {
	var data = {
		"request"     : "get_all_vehicles_legacy",
		"sessionuuid" : req.session.sessionuuid
	};

	jsonsrv.do_jsonsrv2(data,
		function(result) {
			if(result.result === "OK") {
				req.session.cache.vehicles = result.vehicles;
				console.log(req.session.cache.vehicles);
				render_vehicle_use_edit(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_vehicle_use_edit(req, res) {
	if(typeof req.session.cache.vehicles === 'undefined') {
		get_all_vehicles(req, res);
		return;
	}

	var the_vehicle_use = req.session.cache.days[req.params.day].vehicle_use[req.params.vehicle_use];

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

	console.log('render_vehicle_use_edit');
}

router.get('/:day/:vehicle_use/edit', function(req, res, next) {
	if(typeof req.session.cache.days[req.params.day] !== 'undefined') {
		if(typeof req.session.cache.days[req.params.day].vehicle_use[req.params.vehicle_use] !== 'undefined') {
			render_vehicle_use_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.vehicle_use === "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_vehicle_use = pcalutils.create_empty_vehicle_use(uuid);
					req.session.cache.days[req.params.day].vehicle_use[uuid] = new_vehicle_use;

					var pcalview = "";
					if(req.query.pcalview)
						pcalview = '?pcalview='+req.query.pcalview;

					res.redirect('/vehicle_use/'+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"		: "vehicle_use_details",
			"sessionuuid"   : req.session.sessionuuid,
			"date"			: req.params.day,
			"vehicle_use"			: req.params.vehicle_use,
		};

		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].vehicle_use[req.params.vehicle_use] = result.vehicle_use;

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

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

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

module.exports = router;
