/* 
 * Copyright 2017, Emanuel Rabina (http://www.ultraq.net.nz/)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// TODO: This should really be done using a parser generator like PEG.js so that
//       we can discern between the various expression syntaxes and so execute
//       the right functions for handling them.  For now, only assumed
//       expressions are supported, with separate functions for each of those
//       best guesses.

const SIMPLE_NAMED_ITEM_EXPRESSION = /\$\{(.+)\}/;

/**
 * Parses and evaluates a Thymeleaf expression.
 * 
 * @param {String} expression
 * @param {Object} context
 * @return {String} The result of evaluating the expression.
 */
export function processExpression(expression, context) {

	let namedResults = SIMPLE_NAMED_ITEM_EXPRESSION.exec(expression);
	if (namedResults) {
		let itemValue = context ? context[namedResults[1]] : null;
		return (itemValue === null || itemValue === undefined) ? '' : itemValue;
	}
	return expression;
}

const ITERATION_EXPRESSION = /(.+)\s*:\s*(\$\{.+\})/;

/**
 * Parses and evaluates a Thymeleaf iteration expression.
 * 
 * @param {String} expression
 * @param {Object} context
 * @return {Object} Information about the iteration expression.
 */
export function processIterationExpression(expression, context) {

	let expressionParts = ITERATION_EXPRESSION.exec(expression);
	if (expressionParts) {
		return {
			localValueName: expressionParts[1],
			iterable: processExpression(expressionParts[2], context)
		};
	}
	return null;
}

@@ -1107,39 +1107,44 @@
 @param %7BObject%7D 
+%5B
 context
+=%7B%7D%5D
 %0A * @return %7BStr
@@ -1238,32 +1238,36 @@
 ression, context
+ =%7B%7D
 ) %7B%0A%0A%09let namedR
@@ -1364,18 +1364,8 @@
 ue =
- context ?
  con
@@ -1389,15 +1389,8 @@
 %5B1%5D%5D
- : null
 ;%0A%09%09
@@ -1658,23 +1658,28 @@
 Object%7D 
+%5B
 context
+=%7B%7D%5D
 %0A * @ret
@@ -1731,32 +1731,32 @@
 expression.%0A */%0A
-
 export function 
@@ -1801,16 +1801,21 @@
  context
+ = %7B%7D
 ) %7B%0A%0A%09le

Set a default context if none given