package de.saumya.mojo.gem;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.shared.model.fileset.util.FileSetManager;
import org.codehaus.plexus.util.FileUtils;

import de.saumya.mojo.jruby.AbstractJRubyMojo;

/**
 * goal to run gem build
 * 
 * @goal build
 * @requiresProject true
 */
public class BuildMojo extends AbstractJRubyMojo {
    /**
     * 
     * @parameter
     */
    protected final List<Fileset> gemfilesets             = null;

    /**
     * map of dependency where the key is the gemname and value is the version
     * pattern
     * 
     * @parameter
     */
    protected Map<String, String> dependencies            = null;

    /**
     * map of developer dependency where the key is the gemname and value is the
     * version pattern
     * 
     * @parameter
     */
    protected Map<String, String> developmentDependencies = null;

    /**
     * the file location for the generated gemspec
     * 
     * @parameter 
     *            default-value="${project.build.directory}/${project.artifactId}.gemspec"
     */
    private final File            gemSpec                 = null;

    /**
     * temporary directory to collect all the files for the gem
     * 
     * @parameter 
     *            default-value="${project.build.directory}/${project.artifactId}"
     */
    private final File            gemDirectory            = null;

    /**
     * file of the generated jar file
     * 
     * @parameter default-value=
     *            "${project.build.directory}/${project.build.finalName}.jar"
     */
    private final File            jarfile                 = null;

    /**
     * file of the final gem.
     * 
     * @parameter default-value=
     *            "${project.build.directory}/${project.build.finalName}-java.gem"
     */
    private final File            gemFile                 = null;

    public void execute() throws MojoExecutionException {
        build(this.dependencies,
              this.developmentDependencies,
              this.gemfilesets,
              null,
              this.mavenProject.getArtifactId() + "_ext.jar");
    }

    @SuppressWarnings("unchecked")
    protected void build(final Map<String, String> dependencies,
            final Map<String, String> developmentDependencies,
            final List<Fileset> filesets, final String path,
            final String jarName) throws MojoExecutionException {
        GemspecWriter writer = null;
        try {
            writer = new GemspecWriter(this.gemSpec, this.mavenProject, true);
            if (path != null) {
                writer.appendPath(path);
            }
            if (filesets != null) {
                final FileSetManager fileSetManager = new FileSetManager(getLog());
                for (final Fileset fileset : filesets) {
                    getLog().info("copy from '"
                            + fileset.getDirectory()
                            + "': "
                            + Arrays.toString(fileSetManager.getIncludedFiles(fileset)));
                    for (final String file : fileSetManager.getIncludedFiles(fileset)) {
                        writer.appendFile(fileset.getDirectory()
                                + File.separatorChar + file);
                    }
                }
            }
            if (dependencies != null) {
                for (final Map.Entry<String, String> entry : dependencies.entrySet()) {
                    writer.appendDependency(entry.getKey(), entry.getValue());
                }
            }
            if (developmentDependencies != null) {
                for (final Map.Entry<String, String> entry : developmentDependencies.entrySet()) {
                    writer.appendDevelopmentDependency(entry.getKey(),
                                                       entry.getValue());
                }
            }
            writer.appendJarfile(this.jarfile, jarName);
        }
        catch (final IOException e) {
            throw new MojoExecutionException("error writing out the gemspec file",
                    e);
        }
        finally {
            if (writer != null) {
                try {
                    writer.close();
                }
                catch (final IOException e) {
                    // ignore
                }
            }
        }
        if (writer.isUptodate()) {
            getLog().info("gem up to date");
            return;
        }
        try {
            // this.gemDirectory.mkdirs();
            writer.copy(this.gemDirectory);
            // FileUtils.copyFile(this.jarfile,
            // new File(new File(this.gemDirectory, "lib"),
            // jarName));
        }
        catch (final IOException e) {
            throw new MojoExecutionException("error copying files", e);
        }
        execute("-S gem build " + this.gemSpec.getAbsolutePath());
        try {
            FileUtils.copyFile(new File(this.gemDirectory,
                                       this.gemFile.getName()
                                               .replace("-SNAPSHOT", "")),
                               this.gemFile);
        }
        catch (final IOException e) {
            throw new MojoExecutionException("error copying files", e);
        }
    }

    @Override
    protected File launchDirectory() {
        return this.gemDirectory.getAbsoluteFile();
    }

}

@@ -374,21 +374,171 @@
  to 
-run gem build
+build a gem from the given project. must be of type %22gem%22. it takes%0A * the metainfo from the pom alongs with extra configuration of the plugin to%0A * build the gem.
 %0A * 
@@ -2194,32 +2194,107 @@
 tionException %7B%0A
+        if (this.mavenProject.getArtifact().getType().equals(%22gem%22)) %7B%0A    
         build(th
@@ -2302,32 +2302,36 @@
 s.dependencies,%0A
+    
               th
@@ -2364,32 +2364,36 @@
 ,%0A              
+    
 this.gemfilesets
@@ -2412,14 +2412,22 @@
     
+ 
+   
 null,%0A
+    
     
@@ -2493,45 +2493,150 @@
     
-%7D%0A%0A    @SuppressWarnings(%22unchecked%22)
+    %7D%0A        else %7B%0A            getLog().warn(%22building gem is configured but it is not a gem artifact. skip gem building%22);%0A        %7D%0A    %7D%0A
 %0A   

use it only for gem artifacts