package org.codehaus.mojo.versions;

import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.artifact.versioning.OverConstrainedVersionException;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.mojo.versions.api.ArtifactVersions;
import org.codehaus.mojo.versions.api.DefaultVersionsHelper;

/**
 * @goal increment
 * @author djones
 * 
 */
public class IncrementMojo extends SetMojo {

	/**
	 * Gets the latest version of the current artifact, increments the
	 * {@code ArtifactVersion#getIncrementalVersion()} property, and then
	 * re-writes the current POM to use this new version.
	 */
	public void execute() throws MojoExecutionException, MojoFailureException {

		try {
			Artifact currentArtifact = getProject().getArtifact();
			ArtifactVersion currentVersion = currentArtifact.getSelectedVersion();
			ArtifactVersions versions = getHelper().lookupArtifactVersions(currentArtifact, false);
			ArtifactVersion newest = versions.getNewestVersion(currentVersion, null);

			int incrementalVersion = newest.getIncrementalVersion();
			incrementalVersion++;
			
			newVersion = newest.getMajorVersion() + "." + newest.getMinorVersion() + "." + incrementalVersion;
		} catch (OverConstrainedVersionException e) {
			throw new MojoExecutionException("Constraints prevented plug-in from finding latest existing version", e);
		} catch (ArtifactMetadataRetrievalException e) {
			throw new MojoExecutionException("Could not find latest artifact version", e);
		}

		super.execute();
	}
}
