var fs = require('fs');

var admins = {};

var FILENAME		= false;

module.exports.init = function(userfile) {
	FILENAME = userfile;
	module.exports.loadFile();
}

module.exports.loadFile = function() {
	if (!FILENAME) throw "No file for user JSON specified";
    fs.readFile(FILENAME, 'utf8', function(err, data) {
		if (err) throw err;
		admins = JSON.parse(data);
	});
}

module.exports.AdminRight = {
    ADMIN: 1,
    MENU: 2,
    RESERVATION: 3
}

module.exports.checkCredentials = function(name, pwd) {
	if (name && pwd && (name in admins) && pwd==admins[name].pwd) {
		// valid
		return true;
	} else {
		// invalid
		return false;
	}
};

module.exports.hasAccess = function(req, section) {
	var name = module.exports.getName(req);
	return (name && admins[name] && admins[name].rights && admins[name].rights[section] && admins[name].rights[module.exports.AdminRight.ADMIN]);
};

module.exports.getName = function(req) {
	if ((typeof req.session === 'undefined') || (typeof req.session.name === 'undefined'))
		return false;
	else
		return req.session.name;
}

module.exports.doLogin = function(req, name, pwd) {
	if (module.exports.checkCredentials(name, pwd) && !(typeof req.session === 'undefined')) {
		req.session.name = name;
	}
	return module.exports.getName(req);
}

module.exports.doLogout = function(req) {
	if (!(typeof req.session === 'undefined')) {
		req.session.destroy();
	}
	return module.exports.getName(req);
}

