/*
 * Created on 12/03/2003
 *
 * To change this generated comment go to 
 * Window>Preferences>Java>Code Generation>Code Template
 */
package org.apache.maven.ashkelon;

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

/**
 * @author <a href="bwalding@jakarta.org">Ben Walding</a>
 * @version $Id: PackageTool.java,v 1.1 2003/03/12 20:20:29 bwalding Exp $
 */
public class PackageTool
{

    /**
     * Count the number of java files in a directory
     * @param dir
     * @return
     */
    public static int countJavaFiles(File dir)
    {
        FileFilter ff = new FileFilter()
        {
            public boolean accept(File pathname)
            {
                String path = pathname.getName().toLowerCase();
                if (path.endsWith(".java"))
                {
                    return true;
                }

                return false;
            }
        };

        File[] f = dir.listFiles(ff);

        return f.length;

    }
    /**
     * 
     * @param startDir
     * @return a List of String object representing the packages
     */
    public List findPackages(File startDir)
    {
        List results = internalFindPackages(new ArrayList(), startDir);
        //      Now post process them
        List packages = new ArrayList(results.size());

        Iterator resultsIter = results.iterator();
        while (resultsIter.hasNext())
        {
            File f = (File) resultsIter.next();
            String n = f.getAbsolutePath();

            if (n.equals(startDir.getAbsolutePath()))
            {
                //Default package
                packages.add("");
            }
            else
            {

                n = n.substring(startDir.getAbsolutePath().length() + 1);
                n = n.replace('/', '.');
                n = n.replace('\\', '.');
                packages.add(n);
            }
        }
        return packages;
    }

    public File[] getSubDir(File dir)
    {

        FileFilter ff = new FileFilter()
        {
            public boolean accept(File pathname)
            {
                return pathname.isDirectory();
            }
        };
        return dir.listFiles(ff);
    }

    protected List internalFindPackages(List results, File startDir)
    {
        if (countJavaFiles(startDir) != 0)
        {

            results.add(startDir);
        }
        File subdirs[] = getSubDir(startDir);
        for (int i = 0; i < subdirs.length; i++)
        {
            internalFindPackages(results, subdirs[i]);
        }

        return results;
    }
}
