/*
 * jarsProperty.java
 *
 * Created on March 20, 2001, 10:27 AM
 */

package com.sns.tools.ant.taskdefs;

import org.apache.tools.ant.taskdefs.*;
import org.apache.tools.ant.*;
import org.apache.tools.ant.types.*;
import java.util.*;
import java.io.*;

/**
 * Sets a property with the value equal to the path-like list of files included
 * in the filesets.
 *
 *Usage:
 *<pre>
 *  <jars-property property="jars.list">
 *      <fileset dir=".">
 *          <include name="*.jar"/>
 *      </fileset>
 *  </jars-property>
 *</pre>
 *
 * @author  <a href="mailto:John.D.Casey@mail.sprint.com">John Casey</a>
 * @version 1.0
 */
public class JarsProperty extends Taskdef {
    private ArrayList filesets;
    private String property;

    /** Creates new jarsProperty */
    public JarsProperty() {
    }
    
    /**
     * Adds a fileset to the list of included files.
     *
     *@param fs The fileset to include in the list.
     */
    public void addFileset(FileSet fs){
        if(filesets == null){
            filesets = new ArrayList();
        }
        filesets.add(fs);
    }
    
    /**
     * Sets the property name to store the resulting string under.
     *
     *@param property The property name.
     */
    public void setProperty(String property){
        this.property = property;
    }
    
    /**
     * Executes the task.
     */
    public void execute() throws BuildException{
        Iterator it = filesets.iterator();
        FileSet fs = null;
        DirectoryScanner ds = null;
        StringBuffer buf = new StringBuffer();
        String SEP = System.getProperty("path.separator");
        while(it.hasNext()){
            fs = (FileSet)it.next();
            ds = fs.getDirectoryScanner(project);
            File file = null;
            File dir = fs.getDir(project);
            String[] files = ds.getIncludedFiles();
            String jarfile = null;
            for(int i=0; i<files.length; i++){
                jarfile = files[i];
                file = new File(jarfile);
                if (!file.isAbsolute()) {
                    jarfile = (new File(dir, jarfile)).getAbsolutePath();
                    file = (new File(jarfile)) ;
                }
                
                String filename = file.getAbsolutePath();
                if(file.exists() && file.isFile()) {
                    buf.append(file.getAbsolutePath());
                    if(i+1 < files.length){
                        buf.append(SEP);
                    }
                }
            }
        }
        
        if(buf.length() > 0){
            project.setProperty(property, buf.toString());
        }
    }
}
