/*
 * @(#)StyleTransformer.java
 *
 * Copyright (C) 2003-2004 Matt Albrecht
 * groboclown@users.sourceforge.net
 * http://groboutils.sourceforge.net
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the 
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software. 
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL 
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 *  DEALINGS IN THE SOFTWARE.
 */

package net.sourceforge.groboutils.codecoverage.v2.ant;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.w3c.dom.Document;
import org.w3c.dom.Node;


/**
 * Transforms XML with XSL.  Stolen from the JUnit optional task... kind of.
 *
 * @author    Matt Albrecht <a href="mailto:groboclown@users.sourceforge.net">groboclown@users.sourceforge.net</a>
 * @version   $Date: 2004/04/15 05:48:25 $
 * @since     November 22, 2003
 */
public class StyleTransformer
{
    private Project project;
    private Transformer tformer;
    
    public StyleTransformer( Project proj, String stylesheetID, File outDir )
            throws BuildException
    {
        this.project = proj;
        
        try
        {
            TransformerFactory tfactory = TransformerFactory.newInstance();
            Source xslSrc = new StreamSource( stylesheetID );
            this.tformer = tfactory.newTransformer( xslSrc );
            this.tformer.setParameter("output.dir", outDir.getAbsolutePath());
        }
        catch (javax.xml.transform.TransformerConfigurationException e)
        {
            throw new BuildException( "Error creating XSL transformer: "+
                e.getMessage(), e );
        }

    }
    
    
    public void setParameter( String name, Object val )
    {
        this.tformer.setParameter( name, val );
    }
    
    
    
    public Document transform( Document in )
            throws BuildException
    {
        DOMResult result = new DOMResult();
        DOMSource source = new DOMSource( in );
        execute( source, result );
        return getDocument( result.getNode() );
    }
    
    
    public void transform( Document in, File outFile )
            throws BuildException, IOException
    {
        checkFileTree( outFile );
        Source source = new DOMSource( in );
        FileOutputStream fos = null;
        try
        {
            fos = new FileOutputStream( outFile );
            Result result = new StreamResult( fos );
            execute( source, result );
        }
        finally
        {
            if (fos != null)
            {
                fos.close();
            }
        }
    }
    
    
    public Document transform( File in )
            throws BuildException, IOException
    {
        DOMResult result = new DOMResult();
        FileInputStream fis = null;
        try
        {
            fis = new FileInputStream( in );
            Source source = new StreamSource( in );
            execute( source, result );
        }
        finally
        {
            if (fis != null)
            {
                fis.close();
            }
        }
        return getDocument( result.getNode() );
    }
    
    
    public void transform( File in, File outFile )
            throws BuildException, IOException
    {
        checkFileTree( outFile );
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try
        {
            fos = new FileOutputStream( outFile );
            fis = new FileInputStream( in );
            Source source = new StreamSource( fis );
            Result result = new StreamResult( fos );
            execute( source, result );
        }
        finally
        {
            if (fos != null)
            {
                fos.close();
            }
            if (fis != null)
            {
                fis.close();
            }
        }
    }
    
    
    protected final void execute( Source src, Result res )
            throws BuildException
    {
        final long t0 = System.currentTimeMillis();
        tformer.setParameter( "TSTAMP", DateFormat.getDateTimeInstance().
            format( new Date( t0 ) ) );
        try
        {
            tformer.transform( src, res );
        }
        catch (RuntimeException ex)
        {
            throw ex;
        }
        catch (Exception e)
        {
            throw new BuildException( "Errors while applying transformations: "
                + e.getMessage(), e );
        }
        finally
        {
            final long dt = System.currentTimeMillis() - t0;
            this.project.log( "Transform time: " + dt + "ms",
                Project.MSG_DEBUG );
        }
    }
    
    
    private final void checkFileTree( File f )
            throws IOException
    {
        File p = f.getParentFile();
        p.mkdirs();
    }
    
    
    private static Document getDocument( Node child )
    {
        if (child instanceof Document)
        {
            return (Document)child;
        }
        Document doc = child.getOwnerDocument();
        if (doc == null)
        {
            doc = getDocumentBuilder().newDocument();
            Node c = doc.importNode( child, true );
            doc.appendChild( c );
        }
        return doc;
    }
    
    
    private static DocumentBuilder getDocumentBuilder()
    {
        try
        {
            return DocumentBuilderFactory.newInstance().newDocumentBuilder();
        }
        catch (Exception exc)
        {
            throw new ExceptionInInitializerError(exc);
        }
    }
}

