package com.github.markusbernhardt.springcontexttemplate;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.util.StringValueResolver;

public class ImportStringValueResolver implements StringValueResolver {

	/**
	 * The regex pattern used later to match the variables to replace
	 */
	protected final Pattern pattern;

	/**
	 * The map storing all the mappings
	 */
	protected final Map<String, String> mappings;

	/**
	 * Constructor
	 * 
	 * @param map
	 *            the map containing all value to resolved value mappings
	 */
	public ImportStringValueResolver(Map<String, String> mappings) {
		super();
		this.pattern = getPattern(mappings);
		this.mappings = mappings;
	}

	/**
	 * Resolve the given String value, for example parsing placeholders.
	 * 
	 * @param value
	 *            the original String value
	 * @return the resolved String value
	 */
	@Override
	public String resolveStringValue(String value) {
		StringBuffer sb = new StringBuffer();
		Matcher matcher = pattern.matcher(value);
		while (matcher.find()) {
			matcher.appendReplacement(sb, mappings.get(matcher.group(1)));
		}
		matcher.appendTail(sb);
		return sb.toString();
	}

	/**
	 * Build the regex pattern used later to match the variables to replace
	 * 
	 * @param mappings
	 *            the mappingt to match
	 * @return the pattern
	 */
	protected Pattern getPattern(Map<String, String> mappings) {
		String join = "";
		StringBuilder patternString = new StringBuilder();
		patternString.append("\\$\\{(");
		for (String key : mappings.keySet()) {
			patternString.append(join);
			patternString.append(key);
		}
		patternString.append(")\\}");
		return Pattern.compile(patternString.toString());
	}

}

@@ -976,24 +976,91 @@
 ng value) %7B%0A
+%09%09String resolvedValue = value;%0A%0A%09%09do %7B%0A%09%09%09value = resolvedValue;%0A%09
 %09%09StringBuff
@@ -1087,16 +1087,17 @@
 ffer();%0A
+%09
 %09%09Matche
@@ -1132,16 +1132,17 @@
 value);%0A
+%09
 %09%09while 
@@ -1163,16 +1163,17 @@
 )) %7B%0A%09%09%09
+%09
 matcher.
@@ -1229,18 +1229,20 @@
 1)));%0A%09%09
+%09
 %7D%0A
+%09
 %09%09matche
@@ -1261,22 +1261,32 @@
 (sb);%0A%09%09
+%09
 re
-turn
+solvedValue =
  sb.toSt
@@ -1293,16 +1293,83 @@
 ring();%0A
+%09%09%7D while (!value.equals(resolvedValue));%0A%0A%09%09return resolvedValue;%0A
 %09%7D%0A%0A%09/**

Resolve variables in a loop