var fs = require('fs');

var menuJSON = {
	"food": {},
	"drinks": {}
};

var REGEX_CREATE	= /^[fd]-[0-9]+-new$/;
var REGEX_UPDATE	= /^[fd]-[0-9]+-[0-9]+$/;
var REGEX_DELETE	= /^[fd]-[0-9]+-[0-9]+-del$/;

var REGEX_FLOAT		= /^([0-9]+(\.[0-9]+)?)$/;

var LANG = {};
LANG["ACTIONS"] = {
	1: "Das Ertellen des Menüeintrags",
	2: "Das Aktualisieren der Informationen",
	3: "Das Löschen des Menüeintrags"
};
LANG["ERROR_MESSAGES"] = {
	1: "Das Feld \"Name\" darf nicht leer sein.",
	2: "Das Feld \"Beschreibung\" darf nicht leer sein.",
	4: "Das Feld \"Preis\" darf nicht leer und muss eine positive Zahl sein.",
	8: "Beim Verarbeiten der Anfrage ist ein interner Fehler aufgetreten."
};
LANG["MESSAGES"] = {
	"success": "%action% war erfolgreich.",
	"failure": "%action% konnte nicht durchgeführt werden."
};
LANG["INTERNAL"] = {
	"noinput": "No input file for menu JSON specified!"
};

var FILENAME		= false;

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

module.exports.loadFile = function() {
	if (!FILENAME) throw LANG["MESSAGES"]["noinput"];
    fs.readFile(FILENAME, 'utf8', function(err, data) {
		if (err) throw err;
		menuJSON = JSON.parse(data);
	});
}

module.exports.saveJSON = function() {
	if (!FILENAME) throw LANG["MESSAGES"]["noinput"];
	fs.writeFile(FILENAME, JSON.stringify(menuJSON, null, 4), function(err) {
		if(err) {
			console.log(err);
			return false;
		}
	});
	return true;
}

module.exports.MenuAction = {
    ERROR:  0,
    CREATE: 1,
    UPDATE: 2,
    DELETE: 3
}

module.exports.ErrorCode = {
    SUCCESS:       0,
    NOSTRING_NAME: 1,
    NOSTRING_DESC: 2,
    NOFLOAT_PRICE: 4,
	WRONG_ACTION:  8
}
module.exports.ErrorCode["MAX"] = sum(module.exports.ErrorCode);

module.exports.getStatusMessage = function(errorCode, action, nametag) {
	if (action) {
		var position = splitNameTag(nametag, action);
		if (!errorCode) {
			return {
				type: "success",
				message: LANG["MESSAGES"]["success"].replace("%action%", LANG["ACTIONS"][action]),
				reasons: null,
				anchor: menuJSON[position.category][position.section]["anchor"]
			}
		} else {
			var reasons = [];
			for (var i = 1; i < module.exports.ErrorCode["MAX"]; i=i*2) {
				if (errorCode & i) { // bit-wise comparing
					reasons.push(LANG["ERROR_MESSAGES"][i]);
				}
			}
			return {
				type: "danger",
				message: LANG["MESSAGES"]["failure"].replace("%action%", LANG["ACTIONS"][action]),
				reasons: reasons,
				anchor: menuJSON[position.category][position.section]["anchor"]
			}
		}
	} else {
		return null;
	}
}

module.exports.determineAction = function(nametag) {
	if (nametag && REGEX_CREATE.test(nametag)) { // new
		return module.exports.MenuAction.CREATE;
	} else if (nametag && REGEX_UPDATE.test(nametag)) { // update
		return module.exports.MenuAction.UPDATE;
	} else if (nametag && REGEX_DELETE.test(nametag)) { // delete
		return module.exports.MenuAction.DELETE;
	}
	return module.exports.MenuAction.ERROR;
}

module.exports.checkValidity = function(name, desc, price) {
	var errorCode = 0;
	
	if (!name || !(typeof name === 'string' || name instanceof String))
		errorCode += module.exports.ErrorCode.NOSTRING_NAME;
	if (!desc || !(typeof desc === 'string' || desc instanceof String))
		errorCode += module.exports.ErrorCode.NOSTRING_DESC;
	if (isNaN(filterFloat(price)))
		errorCode += module.exports.ErrorCode.NOFLOAT_PRICE;
	return errorCode;
}

module.exports.addValue = function(name, desc, price, nametag) {
	var errorCode = module.exports.checkValidity(name, desc, price);
	var action = module.exports.determineAction(nametag);
	if (action !== module.exports.MenuAction.CREATE) {
		errorCode += module.exports.ErrorCode.WRONG_ACTION;
	}
	if (!errorCode) {
		price = filterFloat(price);
		var position = splitNameTag(nametag, action);
		menuJSON[position.category][position.section]["items"].push({
			name: name,
			desc: desc,
			price: price
		});
		module.exports.saveJSON();
	}
	return errorCode;
}

module.exports.updateValue = function(name, desc, price, nametag) {
	var errorCode = module.exports.checkValidity(name, desc, price);
	var action = module.exports.determineAction(nametag);
	if (action !== module.exports.MenuAction.UPDATE) {
		errorCode += module.exports.ErrorCode.WRONG_ACTION;
	}
	if (!errorCode) {
		price = filterFloat(price);
		var position = splitNameTag(nametag, action);
		menuJSON[position.category][position.section]["items"][position.id] = {
			name: name,
			desc: desc,
			price: price
		};
		module.exports.saveJSON();
	}
	return errorCode;
}

module.exports.deleteValue = function(nametag) {
	var errorCode = module.exports.ErrorCode.SUCCESS;
	var action = module.exports.determineAction(nametag);
	if (action !== module.exports.MenuAction.DELETE) {
		errorCode += module.exports.ErrorCode.WRONG_ACTION;
	}
	if (!errorCode) {
		var position = splitNameTag(nametag, action);
		menuJSON[position.category][position.section]["items"].splice(position.id, 1);
		module.exports.saveJSON();
	}
	return errorCode;
}

module.exports.getJSON = function() {
	return menuJSON;
}

var filterFloat = function(value) {
	if(REGEX_FLOAT.test(value))
		return parseFloat(value);
	return NaN;
}

function sum(obj) {
  var sum = 0;
  for(var el in obj) {
    if(obj.hasOwnProperty(el)) {
      sum += parseFloat(obj[el]);
    }
  }
  return sum;
}

var splitNameTag = function(nametag, action) {
	if (action) {											// create, update & delete
		var splitArr = nametag.split("-");
		var result = {};
		if (splitArr[0] == "f") {
			result.category = "food";
		} else {
			result.category = "drinks";
		}
		result.section = parseInt(splitArr[1]);
		result.type = action;
		if (action == module.exports.MenuAction.CREATE) {	// create
			result.id = null;
		} else {											// update & delete
			result.id = parseInt(splitArr[2]);
		}
		return result;
	} else {
		return false;
	}
}