package org.jerrymouse.gaes.mavenPlugin.archetype;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;

/**
 * after run "mvn archetype:create-from-project" we need run this to change it
 * be gaes's archeype.
 * 
 * @deprecated
 */
public class GaesArchetypeProjectMojo extends AbstractMojo {

	Log log = LogFactory.getLog(getClass());

	/**
	 * The greeting to display.
	 * 
	 * @parameter expression="${gaeArchetpyePom}"
	 *            default-value="${basedir}/target/generated-sources/archetype/pom.xml"
	 */
	File gaeArchetpyePom;

	Patch patch;

	private ModelPatch modelPatch;

	public GaesArchetypeProjectMojo() {
		modelPatch = new ModelPatchImpl();
		PatchReader patchReader = new PatchReader();
		final URL resource = this.getClass().getClassLoader().getResource(
				"GaesArchetypesProject.xml");
		log.trace(resource);
		try {
			patch = patchReader.read((InputStream) resource.getContent());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		try {
			Model model = new MavenXpp3Reader().read(new FileReader(
					gaeArchetpyePom));
			model = modelPatch.patch(model, patch);
			new MavenXpp3Writer().write(new FileWriter(gaeArchetpyePom), model);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}
	}
}
