/*
 * 作成日: 2007/06/10
 */
package net.sourceforge.swingx;

import java.io.File;
import java.util.ArrayList;

import javax.swing.filechooser.FileFilter;


/**
 * 拡張子でファイルを選ぶ。拡張子は複数指定。
 * 使い方：
 *         chooser.addChoosableFileFilter(
 *             new ExtensionFileFilter(new String[] {".csv"},
 *             "カンマ区切り(*.csv)"));
 *         chooser.addChoosableFileFilter(
 *             new ExtensionFileFilter(new String[] {".jpg",".jpeg"},
 *             "JPEGファイル(*.jpg;*.jpeg)"));
*/
public class ExtensionFileFilter extends FileFilter {
	protected ArrayList extensions = new ArrayList();
	protected String desc;
	protected boolean ignoreCase = true;

	public ExtensionFileFilter(String[] exts, String desc, boolean ignoreCase) {
		if (exts != null) {
			for (int i = 0; i < exts.length; i++) {
				this.extensions.add(exts[i]);
			}
		}
		this.desc = desc;
		this.ignoreCase = ignoreCase;
	}
	public ExtensionFileFilter(String[] exts, String desc) {
		this(exts, desc, true);
	}
	public ExtensionFileFilter() {
		this(null, null);
	}

	public void addExtension(String ext) {
		extensions.add(ext);
	}
	public void setDescription(String desc) {
		this.desc = desc;
	}
	public void setExtensions(String[] exts, String desc) {
		for (int i = 0; i < exts.length; i++) {
			this.extensions.add(exts[i]);
		}
		this.desc = desc;
	}
	public boolean accept(File f) {
		//		String ext = ExtensionFileFilter.getExtension(f.getName());
		//		if(ext==null) return false;		// 拡張子がないとき
		if (f.isDirectory())
			return true; // ディレクトリはOK
		String fname = f.getName();
		for (int i = 0; i < extensions.size(); i++) {
			String ext = (String) extensions.get(i);
			if (fname.toLowerCase().endsWith(ext))
				return true;
		}
		return false;
	}

	public static String getExtension(String fname) {
		// 拡張子の取り出しかた
		int pos = fname.lastIndexOf(".");
		if (pos == -1)
			return null;
		return fname.substring(pos); // .ピリオドつきの拡張子
	}

	public String getDescription() {
		return desc;
	}

	public static void main(String[] args) {
		ExtensionFileFilter filter = new ExtensionFileFilter();
		filter.addExtension(".java");
		System.out.println(filter.accept(new File("ExtensionFileFilter.java")));
		System.out.println(
			filter.accept(new File("ExtensionFileFilter.class")));
	}
}
