package osa.attribute.atgrammar.gui.file_choosers;


import java.io.File;
import java.util.HashMap;
import java.util.Iterator;

import javax.swing.filechooser.FileFilter;



public class GenericFileFilter
  extends FileFilter
  {

  private HashMap filters = new HashMap();
  private String description;

  public GenericFileFilter() {}

  public GenericFileFilter(String extension) {
    addExtension(extension);
  }

  public GenericFileFilter(String extension, String description) {
    addExtension(extension);
    setDescription(description);
  }

  public GenericFileFilter(String[] extensions) {
    this(extensions, null);
  }

  public GenericFileFilter(String[] extensions, String description) {
    for (int i = 0; i < extensions.length; i++)
      addExtension(extensions[i]);
    setDescription(description);
  }

  public boolean accept(File f) {
    if (f != null) {
      if (f.isDirectory())
        return true;
      String ext = getExtension(f);
      if (ext != null &&  filters.get(ext) != null)
        return true;
    }
    return false;
  }

  public String getDescription() {
    String fullDescription;
    if (description == null) {
      if (filters.size() == 1) {
        fullDescription = ((String) filters.keySet().iterator().next()).toUpperCase();
        fullDescription += " File";
      } else
        fullDescription = "";
    } else
      fullDescription = description;
    Iterator extensions = filters.keySet().iterator();
    if (extensions != null) {
      fullDescription += " (";
      while(extensions.hasNext())
        fullDescription += "*." + ((String) extensions.next()) + ", ";
      fullDescription = fullDescription.substring(0, fullDescription.length() - 2).trim();
      if (fullDescription.length() > 0)
        fullDescription += ")";
    }
    return fullDescription;
  }

  public void addExtension(String extension) {
    if (extension != null)
      filters.put(extension.toLowerCase(), this);
  }

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

  private String getExtension(File f) {
    if (f != null) {
      try {
        String fileName = f.getName();
        String ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
        if (ext.length() > 0)
          return ext;
      } catch(IndexOutOfBoundsException e) {}
    }
    return null;
  }
  }