/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000 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 acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Ant", and "Apache Software
 *    Foundation" 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"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * 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/>.
 */

package org.apache.tools.ant.taskdefs.optional.sitraka.coverage;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.*;
import org.apache.tools.ant.types.Commandline;
import org.apache.tools.ant.types.CommandlineJava;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.DirectoryScanner;
import java.util.Vector;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

/**
 * Convenient task to run the snapshot merge utility for JProbe Coverage.
 *
 * @author <a href="sbailliez@imediation.com">Stephane Bailliez</a>
 */
public class CovReport extends Task {
/*
jpcoverport [options] -output=file -snapshot=snapshot.jpc
        Generate a report for the indicated snapshot

        -format=(html|text)     defaults to html
                        The format of the generated report
        -type=(executive|summary|detailed|verydetailed) defaults to detailed
                        The type of report to be generated
                        Note, a very detailed report can be VERY large
        -percent=num            Min 0 Max 100 Default 100
                A numeric value for the threshold for printing methods
        -filters=string
                        A comma seperated list of filters to apply to the data
        -output=string  Must be specified
                        The name of the generated output file
        -snapshot=string        Must be specified
                        The name of the snapshot file that is the source to the report
        -sourcepath=string      defaults to .
                        A semi colon seperated list of source paths

/*

    /** coverage home,  mandatory */
    private File home = null;
    
    /** format of generated report, optional */
    private String format = null;

    /** the name of the output snapshot, mandatory */
    private File tofile = null;

    /** type of report, optional */
    private String type = null;

    /** threshold value for printing methods, optional */
    private Integer percent = null;
    
    /** comma separated list of filters (???)*/
    private String filters = null;
   
    /** name of the snapshot file to create report from */
    private File snapshot = null;

    /** sourcepath to use */
    private Path sourcePath = null;

    
    /**
     * set the coverage home. it must point to JProbe coverage
     * directories where are stored native librairies and jars
     */
    public void setHome(File value) {
        this.home = value;
    }

    /** set the format of the report html|text*/
    public void setFormat(String value){
        this.format = value;
    }
    
    /** sets the report type executive|summary|detailed|verydetailed */
    public void setType(String value){
        this.type =  value;
    }

    /** sets the threshold printing method 0-100*/
    public void setPercent(Integer value){
        this.percent = value;
    }
    
    /** set the filters */
    public void setFilters(String values){
        this.filters = values;
    }

    public Path createSourcepath(){
        if (sourcePath == null) {
            sourcePath = new Path(project);
        }
        return sourcePath.createPath();
    }

    public void setSnapshot(File value){
        this.snapshot = value;
    }

    /**
     * Set the output snapshot file
     */
    public void setTofile(File value) {
        this.tofile = value;
    }

    public CovReport() {
    }
    
    /** check for mandatory options */
    protected void checkOptions() throws BuildException {
        if (tofile == null) {
            throw new BuildException("'tofile' attribute must be set.");
        }
        if (snapshot == null) {
            throw new BuildException("'snapshot' attribute must be set.");
        }
        if (home == null) {
            throw new BuildException("'home' attribute must be set to JProbe Coverage home directory");
        }
        File jar = new File(home, "coverage.jar");
        if (!jar.exists()) {
            throw new BuildException("'home' attribute is not set to Coverage home directory: " + home);
        }
        
    }

    public void execute() throws BuildException {
        checkOptions();
        try {
            Commandline cmdl = new Commandline();
            // we need to run Coverage from his directory due to dll/jar issues
            cmdl.setExecutable( new File(home, "jpcovreport").getAbsolutePath() );
            String[] params = getParameters();
            for (int i = 0; i < params.length; i++) {
                cmdl.createArgument().setValue(params[i]);
            }
            
            // use the custom handler for stdin issues
            LogStreamHandler handler = new LogStreamHandler(this,Project.MSG_INFO,Project.MSG_WARN);
            Execute exec = new Execute( handler );
            log(cmdl.toString(), Project.MSG_VERBOSE);
            exec.setCommandline(cmdl.getCommandline());
            int exitValue = exec.execute();
            if (exitValue != 0) {
                throw new BuildException("JProbe Coverage Report failed (" + exitValue + ")");
            }
        } catch (IOException e){
            throw new BuildException("Failed to execute JProbe Coverage Report.", e);
        }       
    }

    protected String[] getParameters(){
        Vector v = new Vector();
        if (format != null) {
            v.addElement("-format=" + format);
        }
        if (type != null) {
            v.addElement("-type=" + type);
        }
        if (percent != null) {
            v.addElement("-percent=" + percent);
        }
        if (filters != null) {
            v.addElement("-filters=" + filters);
        }
        v.addElement("-output=" + project.resolveFile(tofile.getPath()));
        v.addElement("-snapshot=" + project.resolveFile(snapshot.getPath()));
        // as a default -sourcepath use . in JProbe, so use project .
        if (sourcePath == null) {
            sourcePath = new Path(project);
            sourcePath.createPath().setLocation(project.resolveFile("."));
        }
        v.addElement("-sourcepath=" + sourcePath);
        String[] params = new String[v.size()];
        v.copyInto(params);
        return params;
    }

}
