package org.apache.maven.release;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *    "Apache Maven" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    "Apache Maven", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * ====================================================================
 */

import org.apache.commons.io.FileUtils;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.jaxen.XPath;
import org.jaxen.dom4j.Dom4jXPath;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * This is the base class for any tool that attempts to transform fields
 * in the POM. Currently we are using the XML form of the POM and using Jaxen
 * but eventually we will be able to perform the same transformations on
 * POM beans. Jaxen needs to be modified and some serious cleanup needs to
 * go on in Maven internally, but this will serve as a start. An attempt is
 * made to make this tool GUI friendly.
 *
 * @author <a href="mailto:jason@zenplex.com">Jason van Zyl</a>
 *
 * @version $Id: AbstractPomTransformer.java,v 1.8 2003/04/12 08:12:46 dion Exp $
 */
public abstract class AbstractPomTransformer
    implements PomTransformer
{
    /** POM document */
    private File project;

    /** Dom4j document. */
    private Document document;

    /** Output file. */
    private File outputFile;

    /** Properties used in transformNode */
    private Map variables;

    /** Nodes selected for transformation using xpath. */
    private List selectedNodes;

    private List transformations;

    // -------------------------------------------------------------------------
    // Accessors
    // -------------------------------------------------------------------------

    /**
     *
     * @return
     */
    public Map getVariables()
    {
        return variables;
    }

    /**
     *
     * @param variables
     */
    public void setVariables( Map variables )
    {
        this.variables = variables;
    }

    /**
     *
     * @param project
     */
    public void setProject( File project )
    {
        this.project = project;
    }

    /**
     *
     * @return
     */
    public File getProject()
    {
        return project;
    }

    /**
     *
     * @return
     */
    public Document getDocument()
    {
        return document;
    }

    /**
     *
     * @param document
     */
    public void setDocument( Document document )
    {
        this.document = document;
    }

    /**
     *
     * @return
     */
    public File getOutputFile()
    {
        return outputFile;
    }

    /**
     *
     * @param outputFile
     */
    public void setOutputFile( File outputFile )
    {
        this.outputFile = outputFile;
    }

    /**
     *
     * @return
     */
    public List getSelectedNodes()
    {
        if ( selectedNodes == null )
        {
            try
            {
                selectNodes();
            }
            catch ( Exception e )
            {
                // do nothing.
            }
        }
        return selectedNodes;
    }

    /**
     *
     * @param selectedNodes
     */
    public void setSelectedNodes( List selectedNodes )
    {
        this.selectedNodes = selectedNodes;
    }

    /**
     *
     * @return
     */
    public int getSelectedNodeCount()
    {
        return getSelectedNodes().size();
    }

    /**
     *
     * @return
     */
    public List getTransformations()
    {
        if ( transformations == null )
        {
            createTransformations();
        }

        return transformations;
    }

    /**
     *
     */
    public void createTransformations()
    {
        transformations = new ArrayList();

        for ( Iterator i = getSelectedNodes().iterator(); i.hasNext(); )
        {
            Object o = i.next();

            if ( o instanceof Node )
            {
                Transformation transformation = new Transformation( this );
                transformation.setNode( (Node) o );
                transformations.add( transformation );
            }
        }
    }

    /**
     * This is the automated way of transforming the nodes if there is
     * no user interaction involved.
     *
     * @throws Exception If an error occurs while transforming the nodes.
     */
    public void transformNodes()
        throws Exception
    {
        for ( Iterator i = getSelectedNodes().iterator(); i.hasNext(); )
        {
            Object o = i.next();

            if ( o instanceof Node )
            {
                transformNode( (Node) o );
            }
        }
    }

    // ----------------------------------------------------------------------
    // Implementation
    // ----------------------------------------------------------------------

    /**
     *
     * @return
     */
    public abstract String selectNodesXPathExpression();

    /**
     * The XPath expression returned will select the single node
     * within the single node which needs to be transformed.
     *
     * @return
     */
    public abstract String selectNodeXPath();

    /**
     *
     * @param node
     * @return
     * @throws Exception
     */
    public abstract String getNodeContent( Node node )
        throws Exception;

    /**
     *
     * @param node
     * @throws Exception
     */
    public abstract void transformNode( Node node )
        throws Exception;

    /**
     * Update the snapshot version identifiers with actual timestamp versions
     * and write out the POM in its updated form.
     *
     * @throws Exception
     */
    public void selectNodes()
        throws Exception
    {
        SAXReader reader = new SAXReader();
        setDocument( reader.read( getProject() ) );

        // The selecting nodes with the xpath expression will give us a list
        // of dependencies elements where the version element is equal to 'SNAPSHOT'.
        // So we can get any information we need, and alter anything we need to before writing
        // the dom4j document back out.
        XPath xpath = new Dom4jXPath( selectNodesXPathExpression() );
        setSelectedNodes( xpath.selectNodes( getDocument() ) );
    }

    /**
     *
     * @throws Exception
     */
    public void write()
        throws Exception
    {
        OutputStream os = null;

        if ( getOutputFile() != null )
        {
            // Backup the original first.
            FileUtils.copyFile( getOutputFile(), new File( getOutputFile() + ".backup" ) );

            // Now hand of the os.
            os = new FileOutputStream( getOutputFile() );
        }
        else
        {
            os = new PrintStream( System.out );
        }

        OutputFormat format = new OutputFormat();
        format.setIndentSize( 2 );
        format.setNewlines( true );
        format.setTrimText( true );

        XMLWriter writer = new XMLWriter( format );
        writer.setOutputStream( os );
        writer.write( getDocument() );
    }
}
