/**
 * Copyright (C) 2002
 */

package org.objectweb.util.ant;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.MatchingTask;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * This simple task permits to list a set of directories.
 * The result is print on the System.out output.
 *
 * @author Sebastien Chassande-Barrioz
 */
public class Ls extends MatchingTask {

    /**
     * Base directory for the include/exclude expression
     */
	File dir =  null;

    /**
     * name of the property to set
     */
    String propertyName = null;
    
    /**
     * valuer separator for the property
     */
    String separator = ",";
    
    /**
     * Indicates if the search must include simple files
     */
    boolean includeFiles = true;
    
    /**
     * Indicates if the search must include directories
     */
    boolean includeDirectories = false;
    
    public void setPropertyName(String pn) {
        this.propertyName = pn;
    }
    
	public void setSeparator(String separator) {
        this.separator = separator;
    }

    public void setDir(File d) {
		dir = d;
	}

	public void setIncludeDirectories(boolean includeDirectories) {
        this.includeDirectories = includeDirectories;
    }

    public void setIncludeFiles(boolean includeFile) {
        this.includeFiles = includeFile;
    }

    public void execute() throws BuildException {
        ArrayList fileNames = new ArrayList();
        if (includeDirectories) {
            getProject().log("include directories", Project.MSG_DEBUG);
            fileNames.addAll(DirectoryScannerHelper.getSelectedDirectories(
                getDirectoryScanner(dir), getProject()));
        }
        if (includeFiles) {
            getProject().log("include files", Project.MSG_DEBUG);
            fileNames.addAll(DirectoryScannerHelper.getSelectedFiles(
                getDirectoryScanner(dir), getProject()));
        }
        if (propertyName == null || propertyName.trim().length() == 0) {
            getProject().log("no property name", Project.MSG_DEBUG);
            for (Iterator it = fileNames.iterator(); it.hasNext();) {
                String fileName = (String) it.next();
                System.out.println(fileName);
            }
		} else {
            getProject().log("Property name: " + propertyName, Project.MSG_DEBUG);
            StringBuffer sb = new StringBuffer();
            String sep = "";
            for (Iterator it = fileNames.iterator(); it.hasNext();) {
                String fileName = (String) it.next();
                sb.append(sep).append(fileName);
                sep = separator;
            }
            getProject().log("value=" + sb.toString(), Project.MSG_DEBUG);
            getProject().setProperty(propertyName, sb.toString());
        }
	}
}
