package org.greenstone.anttasks;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.PatternSet;

/**
 * PatternSetToFile is an Ant task used to take an Ant PatternSet and output to a
 * file all the files that it encompasses
 * @author Sam McIntosh
 */
public class PatternSetToFile extends Task
{
	//Sets whether or not only the top-level files and folders
	//are stored in the output file
	public boolean _toplevelonly = false;
	
	//The file the set will be written to
	public File _outfile = null;

	//The directory to check the PatternSet within
	public File _dir = null;
	
	//An array of the child PatternSets of this task
	public ArrayList _sets = new ArrayList();

	/**
	 * This function performs the main task
	 */
	public void execute() throws BuildException
	{
		try
		{
			System.out.println("Creating " + _outfile.getAbsolutePath());
			BufferedWriter out = new BufferedWriter(new FileWriter(_outfile));
			for(int i = 0; i < _sets.size(); i++)
			{
				PatternSet set = (PatternSet)_sets.get(i);
				FileSet fs = new FileSet();
				fs.setDir(_dir);
				PatternSet ps = fs.createPatternSet();
				ps.append(set, this.getProject());
				
				DirectoryScanner ds = fs.getDirectoryScanner(this.getProject());
				
				String[] includedFiles = ds.getIncludedFiles();
				
				if(_toplevelonly)
				{
					ArrayList toplevel = new ArrayList();
					
					for(int j = 0; j < includedFiles.length; j++)
					{
						int separatorIndex = includedFiles[j].indexOf(File.separator);
						
						if ( separatorIndex == -1 && includedFiles[j].length() > 0 && !toplevel.contains(toplevel)) {
							toplevel.add(includedFiles[j]);
						}
						else if ( separatorIndex > -1 && includedFiles[j].length() > 0) {
							String path = includedFiles[j].substring(0, separatorIndex);
							if ( !toplevel.contains(path) ) {
								toplevel.add(path);
							}
						}
					}
					includedFiles = (String[])toplevel.toArray(new String[0]);
				}
				
				for (int j = 0; j < includedFiles.length; j++)
				{
					out.write(includedFiles[j] + "\n");
				}
			}
			out.close();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}

	public void setToplevelonly(boolean toplevelonly)
	{
		_toplevelonly = toplevelonly;
	}

	public void setOutfile(File outfile)
	{
		_outfile = outfile;
	}

	public void setDir(File dir)
	{
		_dir = dir;
	}
	
	public void addConfiguredPatternset(PatternSet patternset) 
	{
		if (patternset == null)
		{
			return;
		}
		
		_sets.add(patternset);
	}
}
