/**
 * 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 com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import org.apache.maven.plugins.shade.resource.ResourceTransformer;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Abstract JOnAS Ressource Transformer
 * @author Jeremy Cazaux
 */
public abstract class AbstractJOnASResourceTransformer implements ResourceTransformer {

    /**
     * Logger
     */
    protected Log logger = LogFactory.getLog(this.getClass());

    /**
     * Default constructor
     */
    protected AbstractJOnASResourceTransformer() {
    }

    /**
     * Remove header comment of a Document
     * @param document
     * @return the header comment as a String
     */
    String removeHeaderCommentFromDocument(Document document) {
        List<Node> masterHeaderCommentNodes = new ArrayList<Node>();
        StringBuffer stringBuffer = new StringBuffer("");
        NodeList masterNodes = document.getChildNodes();
        for (int i = 0; i < masterNodes.getLength(); i++) {
            Node node = masterNodes.item(i);
            if (node.getNodeType() ==  Node.COMMENT_NODE) {
                stringBuffer.append("<!--");
                stringBuffer.append(((Comment) node).getNodeValue());
                stringBuffer.append("-->\n");
                masterHeaderCommentNodes.add(node);
            }
        }

        for (Node masterHeaderCommentNode: masterHeaderCommentNodes) {
            document.removeChild(masterHeaderCommentNode);
        }

        return stringBuffer.toString();
    }

    /**
     *
     * Wrtiting Dom Document onto an output streams
     *
     * @param document The document to serialize
     * @param outputstream The outpustream
     * @param lineWidth Max line width
     * @param indenting True if we need to indent the document
     * @param omitXmlDeclaration true if we need to omit Xml declaration
     * @param headerComment The header comment of a document
     */
    public void serializeXML(Document document, OutputStream outputstream, final Integer lineWidth, final boolean indenting,
                             final boolean omitXmlDeclaration, final String headerComment) {

        final String xmlDeclaration = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";

        OutputFormat format = new OutputFormat(document);
        format.setOmitXMLDeclaration(true);
        format.setIndenting(indenting);
        if (indenting) {
            format.setIndent(2);
        }
        if (lineWidth != null) {
            format.setLineWidth(lineWidth);
        } else {
            format.setLineWidth(200);
        }

        OutputStreamWriter outputStreamWriter = null;
        try {
            outputStreamWriter = new OutputStreamWriter(outputstream, "utf-8");
        } catch (UnsupportedEncodingException e) {
            this.logger.error("Cannot create an OutputStreamWriter from the outputstream .", e);
        }

        try {
            outputStreamWriter.write(xmlDeclaration);
        } catch (IOException e) {
            this.logger.error("Cannot write the following string: " + xmlDeclaration + "\n.", e);
        }

        if (headerComment != null) {
            try {
                outputStreamWriter.write(headerComment);
            } catch (IOException e) {
                this.logger.error("Cannot write the following string: " + headerComment + "\n.", e);
            }
        }

        XMLSerializer serializer = new XMLSerializer(outputStreamWriter, format);
        try {
            serializer.serialize(document);
        } catch (IOException e) {
            this.logger.error("Cannot serialize the Dom document .", e);
        }
    }

    /**
     * @param resource The resource
     * @param regex The regex
     * @return true if the resource match the regex. Otherwise false.
     */
    protected boolean matchPattern(String resource, String regex) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(resource);
        return matcher.matches();
    }
}
