package br.inpe.cap.apache.domain;

import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamConverter;

@XStreamAlias("project")
public class MavenProject {
	
	private static final String MAVEN_VARIABLE_MARK = "${";

	@XStreamAlias("dependencies")
	private List<MavenDependency> dependencies = new ArrayList<>();

	@XStreamAlias("properties")
	@XStreamConverter(MavenProjectPropertyConverter.class)
	private List<MavenProjectProperty> properties;
	
	public void setDependencies(List<MavenDependency> dependencies) {
		this.dependencies = dependencies;
	}
	
	public List<MavenDependency> getDependencies() {
		return dependencies;
	}
	
	public void setProperties(List<MavenProjectProperty> properties) {
		this.properties = properties;
	}

	/**
	 * @return Returns an alphabetic sorted {@link ArrayList} of project properties.
	 */
	public List<MavenProjectProperty> getProperties() {
		return properties;
	}

	public void replaceDependencyVariableVersions() {
		dependencies.stream()
			.filter(
				(dependency) -> {
					String version = dependency.getVersion();
					return version != null &&
						   version.startsWith(MAVEN_VARIABLE_MARK);
				})
			.forEach(
				(dependency) -> {
					String variableVersionValue = lookupVersionValue(dependency.getVersion());
					dependency.setVersion(variableVersionValue);
				}
			);
		
	}

	private String lookupVersionValue(String version) {
		String versionVariable = version.substring(version.indexOf(MAVEN_VARIABLE_MARK)+2, version.length()-1);
		String versionValue = null;
		for (MavenProjectProperty mavenProjectProperty : properties) {
			if(mavenProjectProperty.getName().equals(versionVariable)) {
				versionValue = mavenProjectProperty.getValue();
				break;
			}
		}
		return versionValue;
	}
	
}

@@ -557,24 +557,44 @@
 %3E properties
+ = new ArrayList%3C%3E()
 ;%0D%0A%09%0D%0A%09publi
@@ -1511,16 +1511,165 @@
 %0D%0A%09%7D%0D%0A%0D%0A
+%09/**%0D%0A%09 * @param version Reference of dependency version variable%0D%0A%09 * @return Variable value. If not defined, will return original reference%0D%0A%09 */%0D%0A
 %09private
@@ -1825,39 +1825,8 @@
 );%0D%0A
-%09%09String versionValue = null;%0D%0A
 %09%09fo
@@ -1960,22 +1960,14 @@
 %09%09%09%09
-versionValue =
+return
  mav
@@ -2004,26 +2004,18 @@
 %0A%09%09%09
-%09break;
+%7D
 %0D%0A%09%09
-%09
 %7D%0D%0A%09%09
-%7D
 %0D%0A%09%09
@@ -2028,21 +2028,16 @@
  version
-Value
 ;%0D%0A%09%7D%0D%0A%09

Inicializa listas, evita verificação null simplificando o lookupVersionValue.