var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var parseurl = require('parseurl')

var session = require('express-session');
var filestore = require('session-file-store')(session);

var routes = require('./routes/index');
var events = require('./routes/events');
var tevents = require('./routes/tevents');
var away = require('./routes/away');
var keep_in_mind = require('./routes/keep_in_mind');
var todo = require('./routes/todo');
var vehicle_use = require('./routes/vehicle_use');

var pcalpub = require("./routes/pcalpub");

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

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.locals.session = session({
  resave: false, // don't save session if unmodified
  saveUninitialized: false, // don't create session until something stored
  secret: 'shhhh, very secret',
  store: new filestore({})
});

app.use(app.locals.session);

error_func_ = function(req, res, error)
{
	console.log(error);
 	res.redirect('/login');
}

app.use(function restrict(req, res, next)
{
	// get the url pathname
	var pathname = parseurl(req).pathname;

	if (req.session.user || pathname === '/login')
	{
		next();
	}
	else
	{
		if(req.cookies['pfis_login_c'] !== undefined)
		{
			var pfis_login_c = req.cookies.pfis_login_c;

			console.log("Got pfis_login_c: ", pfis_login_c);

			var data =
			{
				"request"		: "auth_from_cookie",
				"pfis_login_c"	: pfis_login_c
			};

			jsonsrv.do_jsonsrv(req, res, data,
				function(req, res, result) {
					console.log(result);
					if(result.authresult === "OK")
					{
						req.session.regenerate(function(){
							req.session.user = result.username;
							req.session.sessionuuid  = result.sessionuuid;
							console.log('rest session.days');
 							req.session.cache = { days : {} };
							req.session.messages = [];
							next();
						});
					}
					else
					{
						console.log("Cookie led not to user; redirecting to login!");
						res.redirect("/login");
					}
				},
				function(error) {
					jsonsrv.handle_jsonconnectionerror(req, res, error);
				});
		}
		else
			res.redirect('/login');
		/*req.session.regenerate(function(){
				req.session.user = "peter";
				req.session.sessionuuid  = "1c8198b4-e488-4975-a8ff-9dd99e9f324a";
				res.redirect("/");
			});*/
	}
});

app.use('/', routes);
app.use('/event', events);
app.use('/tevent', tevents);
app.use('/away', away);
app.use('/keep_in_mind', keep_in_mind);
app.use('/todo', todo);
app.use('/vehicle_use', vehicle_use);

app.use('/pcalpub', pcalpub);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
	var err = new Error('Not Found');
	err.status = 404;
	next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
	app.use(function(err, req, res, next) {
		res.status(err.status || 500);
		res.render('error', {
			message: err.message,
			error: err
		});
	});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
	res.status(err.status || 500);
	res.render('error', {
		message: err.message,
		error: {}
	});
});

module.exports = app;
