package tools.filefilter;

import java.io.File;
import java.io.FileFilter;

;

/**
 * FileFilter which accepts files with given extensions.
 * 
 * @author Martin Pabst, 17.12.2008
 * 
 */
public class FileExtensionFilter implements FileFilter {

	/**
	 * accepted extensions.
	 */
	private String[] extensions;

	/**
	 * description of file filter.
	 */
	private String description;

	/**
	 * setup file filter.
	 * 
	 * @param extensions
	 *            String[] accepted extensions
	 * @param description
	 *            String description of filter
	 */
	public FileExtensionFilter(final String[] extensions,
			final String description) {
		super();
		this.extensions = extensions;
		this.description = description;
	}

	/**
	 * @return true if file-extension is accepted.
	 */
	@Override
	public boolean accept(final File f) {
		if (f.isDirectory()) {
			return false;
		}

		String extension = getExtension(f);
		if (extension != null) {
			for (int i = 0; i < extensions.length; i++) {
				if (extensions[i].compareToIgnoreCase(extension) == 0) {
					return true;
				}
			}
			return false;
		} else {
			return false;
		}
	}

	/*
	 * Get the extension of a file. @param File
	 */
	public static String getExtension(final File f) {
		String ext = null;
		String s = f.getName();
		int i = s.lastIndexOf('.');

		if (i > 0 && i < s.length() - 1) {
			ext = s.substring(i + 1).toLowerCase();
		}
		return ext;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	/**
	 * @return String description of file filter
	 */
	// @Override
	// public String getDescription() {
	//
	// return description;
	// }
}
