package ch.sourcepond.maven.release.pom;

import static java.lang.String.format;

import java.util.List;

import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;

import ch.sourcepond.maven.release.reactor.UnresolvedSnapshotDependencyException;
import ch.sourcepond.maven.release.substitution.VersionSubstitution;

/**
 * @author rolandhauser
 *
 */
@Component(role = Command.class, hint = "UpdateDependencies")
class UpdateDependencies extends Command {
	static final String ERROR_FORMAT = "%s references dependency %s %s";

	@Requirement(role = VersionSubstitution.class)
	private VersionSubstitution substitution;

	void setVersionSubstitution(final VersionSubstitution substitution) {
		this.substitution = substitution;
	}

	@Override
	public final void alterModel(final Context updateContext) {
		final MavenProject project = updateContext.getProject();
		final Model originalModel = project.getOriginalModel();

		for (final Dependency dependency : determineDependencies(originalModel)) {
			if (updateContext.incrementSnapshotVersionAfterRelease()
					|| isSnapshot(substitution.getActualVersion(project, dependency))) {
				try {
					final String versionToDependOn = updateContext
							.getVersionToDependOn(dependency.getGroupId(), dependency.getArtifactId())
							.getVersionToDependOn();
					dependency.setVersion(versionToDependOn);
					log.debug(format(" Dependency on %s rewritten to version %s", dependency.getArtifactId(),
							versionToDependOn));
				} catch (final UnresolvedSnapshotDependencyException e) {
					updateContext.addError(ERROR_FORMAT, project.getArtifactId(), e.artifactId,
							dependency.getVersion());
				}
			} else {
				log.debug(format(" Dependency on %s kept at version %s", dependency.getArtifactId(),
						dependency.getVersion()));
			}
		}
	}

	protected List<Dependency> determineDependencies(final Model originalModel) {
		return originalModel.getDependencies();
	}
}

@@ -1180,16 +1180,105 @@
 del)) %7B%0A
+%09%09%09final String substitutedVersion = substitution.getActualVersion(project, dependency);%0A
 %09%09%09if (u
@@ -1328,22 +1328,17 @@
 elease()
-%0A%09%09%09%09%09
+ 
 %7C%7C isSna
@@ -1356,49 +1356,17 @@
 itut
-ion.getActualVersion(project, dependency)
+edVersion
 )) %7B
@@ -1858,39 +1858,27 @@
 tId,
-%0A%09%09%09%09%09%09%09dependency.get
+ substituted
 Version
-()
 );%0A%09
@@ -1900,32 +1900,39 @@
 %7B%0A%09%09%09%09log.debug(
+%0A%09%09%09%09%09%09
 format(%22 Depende
@@ -1993,38 +1993,27 @@
 d(),
-%0A%09%09%09%09%09%09dependency.get
+ substituted
 Version
-()
 ));%0A
@@ -2150,9 +2150,8 @@
 ();%0A%09%7D%0A%7D
-%0A

Print substituted version into log