var parser = function(input) {
	var dictionary = {
		"nutella" : 0,
		"kakao" : 0,
		"fahej" : 0,
		"lekvar" : 0,
		"turo" : 0
	};

	if (input === undefined) {
		return {
			order : dictionary,
			probability : 0
		}
	}

	var pancake = input.toLowerCase()
		.split(' ').join('');

	var done = false;
	var n = 0;
	while (!done && pancake.length > "") {
		done = true;
		Object.getOwnPropertyNames(dictionary)
			.forEach(function(flavour){
				var common = getLongestCommonSubstring(pancake, flavour);
				if (common.length > 2) {
					done = false;
					pancake = pancake.replace(common, "");
					dictionary[flavour] += 1;
					n += 1;
				}
			});
	}

	return {
			order : dictionary,
			probability : n === 0 ? 0 : 1 - ((input.length - pancake.length) / (n * input.length))
		};
}

function getLongestCommonSubstring(stringA, stringB) {
	var rowChars = [''].concat(stringA.split(''));
	var rowLength = rowChars.length;
	var colChars = [''].concat(stringB.split(''));
	var colLength = colChars.length;
	var table = [];
	var longest = {
		len : 0,
		row: 0,
		col : 0,
	};

	for (var rowIndex = 0; rowIndex < rowLength; rowIndex++) {
		var row = new Array(colLength);
		row.fill(0);
		table.push(row);
	}

	for (var rowIndex = 1; rowIndex < rowLength; rowIndex++) {
		for (var colIndex = 1; colIndex < colLength; colIndex++) {
			if (rowChars[rowIndex] == colChars[colIndex]) {
				var len = table[rowIndex-1][colIndex-1] + 1;
				table[rowIndex][colIndex] = len;
				if (longest.len < len) {
					longest.len = len;
					longest.row = rowIndex;
					longest.col = colIndex;
				}
			} else {
				table[rowIndex][colIndex] = 0;
			}
		}
	}

	function aggregate(row, col, acc) {
		if (row < 1 || col < 1 || table[row][col] === 0) {
			return acc;
		} else {
			return aggregate(row-1, col-1, acc) + rowChars[row];
		}
	}

	return aggregate(longest.row, longest.col, "");
}

module.exports = parser;
