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

var menuJSON;

var app = express();

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

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'));

fs.readFile(app.get('rundir') + '/data/menu.json', 'utf8', function (err, data) {
	if (err) throw err;
	menuJSON = JSON.parse(data);
});

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

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: menuJSON
	});
});

app.post('/speisekarte', function(req, res) {
	var del = req.body.del;
	var item = req.body.nametag;
	var name = req.body.name;
	var desc = req.body.desc;
	var price = req.body.price;
	if (item && /^[fd]-[0-9]+-new$/.test(item)) { // new
		var splitArr = item.split("-");
		if (splitArr[0] == "f") {
			splitArr[0] = "food";
		} else {
			splitArr[0] = "drinks";
		}
		price = parseInt(price);
		menuJSON[splitArr[0]][parseInt(splitArr[1])]["items"].push({
			name: name,
			desc: desc,
			price: price
		});
	} else if (item && /^[fd]-[0-9]+-[0-9]+$/.test(item)) { // edit
		var splitArr = item.split("-");
		if (splitArr[0] == "f") {
			splitArr[0] = "food";
		} else {
			splitArr[0] = "drinks";
		}
		price = parseInt(price);
		menuJSON[splitArr[0]][parseInt(splitArr[1])]["items"][parseInt(splitArr[2])] = {
			name: name,
			desc: desc,
			price: price
		};
	} else if (del && /^[fd]-[0-9]+-[0-9]+$/.test(del)) { // delete
		var splitArr = del.split("-");
		if (splitArr[0] == "f") {
			splitArr[0] = "food";
		} else {
			splitArr[0] = "drinks";
		}
		menuJSON[splitArr[0]][parseInt(splitArr[1])]["items"].splice(parseInt(splitArr[2]), 1);
	}
	
	res.render('menu', {
		title: 'Restaurant Reiskorn | Speisekarte',
		loginName: loginMod.getName(req),
		isAdmin: loginMod.hasAccess(req, loginMod.AdminRight.MENU),
		menuJSON: menuJSON
	});
	
	fs.writeFile(app.get('rundir') + '/data/menu.json', JSON.stringify(menuJSON, null, 4), function(err) {
		if(err) {
			console.log(err);
		}
	}); 
});

app.get('/kontakt', function(req, res) {
	res.render('contact', {
		title: 'Restaurant Reiskorn | Kontakt',
		loginName: loginMod.getName(req),
		menuJSON: menuJSON
	});
});

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: menuJSON
	});
});

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: menuJSON,
		loginAction: action
	});
});

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

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