package pregozip;

import java.util.Vector;

/*******************************************************************************
 * <p>Class FileFilter</p>
 * <p>Copyright: Copyright (c) 2002</p>
 * @author Markus Wilthaner
 * @version 1.0
 * <p>Offers a filter for filenames. Simply add filters by calling add() and
 * check if a filename meets the criteria with boolean matches().</p>
 *******************************************************************************
 */

public class FileFilter extends Vector {

 /*****************************************************************************
  * <p>Basic constructor</p>
  *****************************************************************************/
  public FileFilter() {
    super();
  }


 /*****************************************************************************
  * <p>add (String newFilter) </p>
  * <p>Adds a new filter to the class. Also converts special characters in the
  * string in a regular expression.</p>
  * <p>Throws an Exception if there is not enough memory.</p>
  *****************************************************************************/
  public void add(String newFilter) throws Exception {

    // Replace every occurence of . in filter with \. (. is a special symbol in regex)
    newFilter = newFilter.replaceAll("\\.", "\\\\.");

    // Replace every occurence of * in filter with .* (for regex)
    newFilter = newFilter.replaceAll("\\*", ".*");

    super.add(newFilter);
  }

 /*****************************************************************************
  * <p>boolean matches (String newFile)</p>
  * <p>Tries to match the Filename to one of the filters. If at least one filter
  * matches the filename, the function returns true.
  *****************************************************************************/
  public boolean matches(String newFile) {
    if(size()>0) {
      for(int i=0; i < size(); i++) {
        if(newFile.matches(get(i).toString())) {
          return true;
        }
      }
    }
    return false;
  }
}
