import org.apache.tools.ant.Task;
import org.apache.tools.ant.BuildException;
import java.util.Vector;
import java.util.ArrayList;
import java.io.File;

public class SrcVersion extends Task {

    String mPropertyName;
    String mLibVersion;
    String mSrcPath;

    public void execute() throws BuildException
    {
        // if property was already set, there's no point in  continuing
        if (getProject().getProperty(mPropertyName) != null)
        {
            return;
        }

        /*
        log("Passed in property: " + mPropertyName);
        log("Passed in libversion: " + mLibVersion);
        log("Passed in srcpath: " + mSrcPath);
        */

        float srcVersion = 0.0f;
        float libVersion;
        float curVersion; 

        // make sure they passed in a number
        try
        {
            libVersion = Float.parseFloat(mLibVersion);
        }
        catch (NumberFormatException nfx)
        {
            throw new BuildException("'libversion' attribute must be float", getLocation());
        }

        // loop over the directories in the srcpath
        File root = new File(mSrcPath);
        File[] files = null;
        if (root.canRead() && root.isDirectory())
        {
            files = root.listFiles();
            for (int i=0; i<files.length; i++)
            {
                // discard anything that's not a directory and not a version number
                if (files[i].isDirectory())
                {
                    try
                    {
                        curVersion = Float.parseFloat(files[i].getName());
                    }
                    catch (NumberFormatException nfx)
                    {
                        //log("Ignoring: " + files[i].getName());
                        continue;
                    }

                    // find the closest src version without exceeding the lib version
                    if (curVersion > libVersion)
                    {
                        //log("Ignoring: " + curVersion);
                    }
                    else if (curVersion < srcVersion)
                    {
                        //log("Ignoring: " + curVersion);
                    }
                    else
                    {
                        srcVersion = curVersion;
                    }
                }
            }
        }
        
        // if no source version was found, don't set the property
        if (srcVersion != 0.0f)
        {
            getProject().setProperty(mPropertyName, Float.toString(srcVersion));
            return;
        }
        //throw new BuildException("no suitable src version could be found for lib version: " + mLibVersion, getLocation());
    }

    public void setProperty(String name)
    {
        mPropertyName = name;
    }

    public void setLibVersion(String version)
    {
        mLibVersion = version;
    }

    public void setSrcPath(String path)
    {
        mSrcPath = path;
    }
}
