package me.automationdomination.plugins.threadfix.service;

import hudson.EnvVars;

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

public class WindowsEnvironmentVariableParsingService implements EnvironmentVariableParsingService {
	
	private final Pattern environmentVariablePattern = Pattern.compile("%.+?%");

	@Override
	public String parseEnvironentVariables(final EnvVars envVars, final String value) {
		final Matcher matcher = environmentVariablePattern.matcher(value);
		
		String parsedValue = value;
		
		while (matcher.find()) {
			final String matchedValue = matcher.group();
			
			// TODO: can this be done more efficiently?
			final String environmentVariableKey = matchedValue.replaceAll("%", "");
			
			final String environmentVariableValue = envVars.get(environmentVariableKey);
			
			// if this is null, that means the environment variable was not found
			if (environmentVariableValue != null) {
				// TODO: can this be done more efficiently?
				parsedValue = parsedValue.replaceAll("%" + environmentVariableKey + "%", environmentVariableValue);
			}
		}
		
		return parsedValue;
	}

}

@@ -729,30 +729,24 @@
 %22%22);%0A%09%09%09%0A%09%09%09
-final 
 String envir
@@ -924,16 +924,82 @@
 null) %7B%0A
+%09%09%09%09environmentVariableValue.replaceAll(%22%5C%5C%5C%5C%22, %22%5C%5C%5C%5C%5C%5C%5C%5C%22);%0A%09%09%09%09%0A
 %09%09%09%09// T

fix for slashes in Windows paths