/*
 * @(#)SimpleXslReportStyle.java
 *
 * Copyright (C) 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.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Vector;

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



/**
 * Describes a report style, used to generate readable reports from the
 * XML output.
 *
 * @author    Matt Albrecht <a href="mailto:groboclown@users.sourceforge.net">groboclown@users.sourceforge.net</a>
 * @version   $Date: 2004/04/15 05:48:25 $
 * @since     March 15, 2004
 */
public class SimpleXslReportStyle implements IReportStyle
{
    private File outdir;
    private boolean removeEmpties = false;
    private StyleTransformer styleRemove = null;
    private StyleTransformer styleHtml = null;
    private String prefix = "CoverageReport-";
    private String suffix = ".html";
    private File styleFile = null;
    private String styleUrl = null;
    private Vector params = new Vector();
    
    
    public static final class ParamType
    {
        String name;
        String expr;
        String ifProp;
        String elseProp;
        
        
        public void setName( String n )
        {
            this.name = n;
        }
        
        public void setExpression( String x )
        {
            this.expr = x;
        }
        
        public void setIf( String i )
        {
            this.ifProp = i;
        }
        
        public void setElse( String e )
        {
            this.elseProp = e;
        }
        
        public void updateParameter( StyleTransformer st, Project p )
        {
            if (this.ifProp != null && p.getProperty( this.ifProp ) == null)
            {
                p.log( "Ignoring parameter '"+this.name+"' because property '"+
                    this.ifProp+"' was not set.", Project.MSG_VERBOSE );
                return;
            }
            if (this.elseProp != null && p.getProperty( this.elseProp ) != null)
            {
                p.log( "Ignoring parameter '"+this.name+"' because property '"+
                    this.elseProp+"' was set.", Project.MSG_VERBOSE );
                return;
            }
            
            st.setParameter( this.name, this.expr );
        }
    }
    
    
    
    public void setPrefix( String p )
    {
        if (p == null)
        {
            p = "";
        }
        this.prefix = p;
    }
    
    
    public void setSuffix( String s )
    {
        if (s == null)
        {
            s = "";
        }
        this.suffix = s;
    }
    
    
    public void setDestDir( File dir )
    {
        this.outdir = dir;
    }
    
    
    public void setRemoveEmpty( boolean on )
    {
        this.removeEmpties = on;
    }
    
    
    public void setStyle( File f )
    {
        this.styleFile = f;
    }
    
    
    public void setStyleURL( String url )
    {
        this.styleUrl = url;
    }
    
    
    public void addParam( ParamType pt )
    {
        if (pt != null)
        {
            this.params.addElement( pt );
        }
    }
    
    
    
    /**
     * Called when the task is finished generating all the reports.  This
     * may be useful for styles that join all the reports together.
     */
    public void reportComplete( Project project, Vector errors )
            throws BuildException, IOException
    {
        // free up memory
        this.styleHtml = null;
        this.styleRemove = null;
    }
    
    
    public void generateReport( Project project, Document doc,
            String moduleName )
            throws BuildException, IOException
    {
        project.log( "Generating XSL report for module "+moduleName,
            Project.MSG_VERBOSE );
        if (this.removeEmpties)
        {
            project.log( "Removing empty methods and classes...",
                Project.MSG_DEBUG );
            doc = getRemoveEmptiesStyle( project ).transform( doc );
        }
        project.log( "Transforming...",
            Project.MSG_DEBUG );
        this.outdir.mkdirs();
        File outFile = new File( this.outdir,
            this.prefix + moduleName + this.suffix );
        getHtmlStyle( project ).transform( doc, outFile );
    }
    
    
    protected StyleTransformer getRemoveEmptiesStyle( Project project )
            throws IOException
    {
        if (this.styleRemove == null && this.removeEmpties)
        {
            this.styleRemove = new StyleTransformer( project,
                getStylesheetSystemIdForClass( "remove-empty-classes.xsl" ),
                this.outdir );
        }
        return this.styleRemove;
    }
    
    
    protected StyleTransformer getHtmlStyle( Project project )
            throws IOException
    {
        if (this.styleHtml == null)
        {
            this.styleHtml = new StyleTransformer( project,
                getStylesheetSystemId(),
                this.outdir );
            Enumeration e = this.params.elements();
            while (e.hasMoreElements())
            {
                ((ParamType)e.nextElement()).updateParameter(
                    this.styleHtml, project );
            }
        }
        return this.styleHtml;
    }
    
    
    /**
     * Get the systemid of the appropriate stylesheet based on its
     * name and styledir. If no styledir is defined it will load
     * it as a java resource in the xsl child package, otherwise it
     * will get it from the given directory.
     *
     * @throws IOException thrown if the requested stylesheet does
     * not exist.
     */
    protected String getStylesheetSystemId()
            throws IOException
    {
        URL url = null;
        if (this.styleFile == null)
        {
            if (this.styleUrl == null)
            {
                throw new BuildException(
                    "No URL or file defined for XSL style sheet." );
            }
            url = new URL( this.styleUrl );
        }
        else
        {
            if (!this.styleFile.exists())
            {
                throw new java.io.FileNotFoundException(
                    "Could not find file '" + this.styleFile + "'" );
            }
            url = new URL( "file", "", styleFile.getAbsolutePath() );
        }
        return url.toExternalForm();
    }
    
    
    protected String getStylesheetSystemIdForClass( String xslname )
            throws IOException
    {
        URL url = getClass().getResource( "xsl/" + xslname );
        if (url == null)
        {
            throw new java.io.FileNotFoundException(
                "Could not find jar resource " + xslname);
        }
        return url.toExternalForm();
    }
}

