var express = require('express');
var jade = require('jade');
var bodyParser = require('body-parser');
var session = require('express-session');
var loginMod = require('./modules/login');
var menuMod = require('./modules/menu');
var reservationMod = require('./modules/reservation');
var fs = require('fs');

var app = express();




// **************************
//   APP VARS
// **************************

app.set('view engine', 'jade');
app.set('rundir', __dirname);
app.set('views', app.get('rundir') + '/views');




// **************************
//   MIDDLEWARE
// **************************

app.use(session({
	secret: 'Jk0Z850cD2MXkcIRXDg1M4X6c1VKkJTb6VYQfbWUKw2XwqaBmqqaKu7K0Q8WlGZVqupF2fzXaavt1hNf',
    resave: true,
    saveUninitialized: true}));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
	extended: true
})); 

app.use('/bin', express.static(app.get('rundir') + '/public'));




// **************************
//   INIT
// **************************

loginMod.init(app.get('rundir') + '/data/users.json');
menuMod.init(app.get('rundir') + '/data/menu.json');
reservationMod.init(app.get('rundir') + '/data/reservation.json');




// **************************
//   ROUTES
// **************************

app.get('/', function(req, res) {
	res.render('index', {
		title: 'Restaurant Reiskorn | Home',
		loginName: loginMod.getName(req),
		menuJSON: menuMod.getJSON()
	});
});

app.get('/speisekarte', function(req, res) {
	res.render('menu', {
		title: 'Restaurant Reiskorn | Speisekarte',
		loginName: loginMod.getName(req),
		isAdmin: loginMod.hasAccess(req, loginMod.AdminRight.MENU),
		menuJSON: menuMod.getJSON()
	});
});

app.post('/speisekarte', function(req, res) {
	var nametag = req.body.nametag;
	var name = req.body.name;
	var desc = req.body.desc;
	var price = req.body.price;
	
	if (loginMod.hasAccess(req, loginMod.AdminRight.MENU)) {
		var action = menuMod.determineAction(nametag);
		var error = 0;
		if (action == menuMod.MenuAction.CREATE)
			error = menuMod.addValue(name, desc, price, nametag);
		else if (action == menuMod.MenuAction.UPDATE)
			error = menuMod.updateValue(name, desc, price, nametag);
		else if (action == menuMod.MenuAction.DELETE)
			error = menuMod.deleteValue(nametag);
	}
	
	res.render('menu', {
		title: 'Restaurant Reiskorn | Speisekarte',
		loginName: loginMod.getName(req),
		isAdmin: loginMod.hasAccess(req, loginMod.AdminRight.MENU),
		menuJSON: menuMod.getJSON(),
		statusMessage: menuMod.getStatusMessage(error, action, nametag)
	});
});

app.get('/kontakt', function(req, res) {
	var showItem = null;
	var nametag = req.query.nametag;
	if (loginMod.hasAccess(req, loginMod.AdminRight.RESERVATION)) {
		var action = reservationMod.determineAction(nametag);
		if (action == reservationMod.MenuAction.SHOW) {
			showItem = reservationMod.showValue(nametag);
		}
	}
	res.render('contact', {
		title: 'Restaurant Reiskorn | Kontakt',
		loginName: loginMod.getName(req),
		isAdmin: loginMod.hasAccess(req, loginMod.AdminRight.RESERVATION),
		menuJSON: menuMod.getJSON(),
		editItem: showItem,
		listItem: reservationMod.getJSON()["items"]
	});
});

app.post('/kontakt', function(req, res) {
	var nametag = req.body.nametag;
	var name = req.body.name;
	var desc = req.body.desc;
	var email = req.body.email;
	var person = req.body.person;
	var time = req.body.time;
	var date = req.body.date;
	
	var action = reservationMod.determineAction(nametag);
	var error = 0;
	var showItem = null;
	
	if (action == reservationMod.MenuAction.CREATE) {
		error = reservationMod.addValue(name, desc, person, email, date, time, nametag);
		if (error) {
			showItem = {
				name: name,
				desc: desc,
				email: email,
				person: person,
				time: time,
				date: date
			};
		}
	}
	else if (loginMod.hasAccess(req, loginMod.AdminRight.RESERVATION)) {
		if (action == reservationMod.MenuAction.UPDATE) {
			error = reservationMod.updateValue(name, desc, person, email, date, time, nametag);
			if (error) {
				showItem = {
					name: name,
					desc: desc,
					email: email,
					person: person,
					time: time,
					date: date,
					id: nametag
				};
			}
		}
		else if (action == reservationMod.MenuAction.DELETE)
			error = reservationMod.deleteValue(nametag);
		else if (action == reservationMod.MenuAction.READ)
			error = reservationMod.readValue(nametag);
	}
	
	res.render('contact', {
		title: 'Restaurant Reiskorn | Kontakt',
		loginName: loginMod.getName(req),
		isAdmin: loginMod.hasAccess(req, loginMod.AdminRight.RESERVATION),
		menuJSON: menuMod.getJSON(),
		editItem: showItem,
		listItem: reservationMod.getJSON()["items"],
		statusMessage: reservationMod.getStatusMessage(error, action)
	});
});

app.get('/login', function(req, res) {
	res.render('login', {
		title: 'Restaurant Reiskorn | Login',
		loginName: loginMod.getName(req),
		isAdmin: loginMod.hasAccess(req, loginMod.AdminRight.ADMIN),
		menuJSON: menuMod.getJSON()
	});
});

app.post('/login', function(req, res) {
	var name = req.body.username;
	var pwd = req.body.password;
	var targetLogout = req.body.targetLogout;
	var action;
	// login
	if (name && pwd) {
		if (loginMod.doLogin(req, name, pwd)) {
			action = "login-success";
		} else {
			action = "login-fail";
		}
	}
	// logout
	if (targetLogout) {
		loginMod.doLogout(req);
		action = "logout";
	}
	
	res.render('login', {
		title: 'Restaurant Reiskorn | Login',
		loginName: loginMod.getName(req),
		isAdmin: loginMod.hasAccess(req, loginMod.AdminRight.ADMIN),
		menuJSON: menuMod.getJSON(),
		loginAction: action
	});
});

app.get('/api/specialOffer.json', function(req, res) {
	res.json({ rice: "Neuer Waldreis" });
});

var server = app.listen(3000, function() {
	var host = server.address().address;
	var port = server.address().port;

	console.log('App listening at http://%s:%s', host, port);
});