package com.zanthan.ant;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.util.StringTokenizer;

import org.apache.tools.ant.util.FileNameMapper;

public class PackageFileMapper
    implements FileNameMapper {

    private char fileNameSep = File.pathSeparatorChar;
    private String from = null;
    private String to = null;

    /**
     * From is the directory containing the files to be mapped.
     * @param s the name of the directory containing the source files
     */
    public void setFrom(String s) {
	this.from = s;
    }

    /**
     * This parameter is ignored by this mapper.
     * @param s ignored
     */
    public void setTo(String s) {
	this.to = s;
    }

    /**
     * Transform the input file name to an output file name using the java package
     * statement found within 15 lines of the top of the file.
     * @param s the input file name, without directory
     * @return a single output file name, if one can be calculated, otherwise null
     */
    public String[] mapFileName(String s) {

	String fileName = from + fileNameSep + s;
	File file = new File(fileName);
	if (!file.exists())
	    return null;
	try {
	    BufferedReader br = new BufferedReader(new FileReader(file));
	    int i = 0;
	    while (i++ < 15) {
		String line = br.readLine();
		StringTokenizer st = new StringTokenizer(line);
		if (st.countTokens() != 2)
		    continue;
		if (!st.nextToken().equals("package"))
		    continue;
		String packageName = st.nextToken();
		if (!packageName.endsWith(";"))
		    continue;
		String packageDirName = 
		    packageName.substring(0, packageName.length() - 1).replace('.', fileNameSep);
		return new String[]{packageDirName + fileNameSep + s};
	    }
	    return null;
	} catch (FileNotFoundException e) {
	    return null;
	} catch (IOException e) {
	    return null;
	}
    }
}

