/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2011 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.tools.maven.shade.transformers;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.plexus.util.IOUtil;
import org.ow2.util.maven.plugin.mergeproperties.Resource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;

/**
 * This class merge antlib fragments into one.
 *
 * @author Jeremy Cazaux
 */
public class AntLibResourceTransformer extends AbstractJOnASResourceTransformer {

    /**
     * Antlib pattern
     */
    public static final String ANTLIB_PATTERN = "antlib-.*[.]xml";

    /**
     * Antlib master file
     */
    public static final String MASTER_FILE = "antlib-master.xml";

    /**
     * The output file
     */
    protected String outputFile;

    /**
     * The master file
     */
    protected Resource masterResource;

    /**
     * Template files
     */
    protected List<Resource> templateResources;

    /**
     * Default constructor
     */
    public AntLibResourceTransformer() {
        this.templateResources = new ArrayList<Resource>();
    }

    /**
     * @param resource
     * @return true if the resource is an antlib resource. Otherwise false
     */
    private boolean isAntlibResource(String resource) {
        return matchPattern(resource, ANTLIB_PATTERN);
    }


    /**
     * @param resource
     * @return true if the resource is an antlib fragment
     */
    public boolean canTransformResource(String resource) {
        return isAntlibResource(resource);
    }

    /**
     *
     * @param resource  The ressource
     * @param is The InputStream associated to the resource
     * @param relocators The list of relocators
     * @throws IOException
     */
    public void processResource(String resource, InputStream is, List relocators) throws IOException {

        this.logger.info("Processing resource " + resource);
        InputStream byteArrayInputStream = new ByteArrayInputStream(IOUtil.toByteArray(is));
        Resource res = new Resource();
        res.setBufferedReader(byteArrayInputStream);
        res.setName(resource);

        if (resource.equals(MASTER_FILE)) {
            this.masterResource = res;
        } else {
            this.templateResources.add(res);
        }
    }

    /**
     * @return true if there is transformed ressource. Otherwise false.
     */
    public boolean hasTransformedResource() {
        return (this.masterResource != null);
    }

    /**
     * Merge all resources into one
     * @param os The JarOutputStream
     * @throws IOException
     */
    public void modifyOutputStream(JarOutputStream os)  {
        ByteArrayInputStream antLibResource = null;
        try {
            //merge antlib fragment into one
            antLibResource = this.mergeAntLib();
        } catch (MojoExecutionException e) {
            this.logger.info("" + e);
        } catch (MojoFailureException e) {
            this.logger.info("" + e);
        }

        //insert antlib file into the uber jar
        try {
            os.putNextEntry(new JarEntry(this.outputFile));
        } catch (IOException e) {
            this.logger.error("Cannot add a new JarEntry .", e);
        }
        try {
            IOUtil.copy(antLibResource, os);
        } catch (IOException e) {
            this.logger.error("Cannot copy antLibResource .", e);
        }
    }

    /**
     * Main method of the plugin
     * @throws org.apache.maven.plugin.MojoExecutionException
     * @throws org.apache.maven.plugin.MojoFailureException
     */
    private ByteArrayInputStream mergeAntLib() throws MojoExecutionException, MojoFailureException {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db;
        Document masterDom;
        ByteArrayInputStream byteInputStream = null;
        String headerComment = null;

        try {
            db = dbf.newDocumentBuilder();

            try {
                masterDom = db.parse(this.masterResource.getInputStream());
                Element rootElement = masterDom.getDocumentElement();

                //remove header comment node of the master
                headerComment = removeHeaderCommentFromDocument(masterDom);

                //append child node
                List<Node> nodes = new ArrayList<Node>();
                for (Resource template: this.templateResources) {

                    this.logger.info("Merging template " + template.getName() + "...");

                    Document templateDom = null;
                    try {
                        templateDom = db.parse(template.getInputStream());
                    } catch (SAXException e) {
                        this.logger.error("Cannot parse " + template.getName() + ".", e);
                    }
                    Element element = templateDom.getDocumentElement();
                    NodeList nl = element.getChildNodes();

                    for (int  i = 0; i < nl.getLength(); i++) {
                        nodes.add(nl.item(i));
                    }
                }
                for (Node node: nodes) {
                    rootElement.appendChild(masterDom.importNode(node, true));
                }

                ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                serializeXML(masterDom, buffer, null, true, false, headerComment);
                byteInputStream = new ByteArrayInputStream(buffer.toByteArray());

            } catch (SAXException e) {
                this.logger.error("Cannot parse " + this.masterResource.getName() + ".", e);
            }

        } catch (ParserConfigurationException e) {
                this.logger.info("." + e);
        } catch (IOException e) {
                this.logger.info("." + e);
        }
;
        return byteInputStream;
    }

    /**
     * Initialize the output file
     * @param outputFile The output file
     */
    public void setOutputFile(String outputFile) {
        this.outputFile = outputFile;
    }
}
