/*
 * Copyright (C) 2007-2009 KenD00
 * 
 * This file is part of DumpHD.
 * 
 * DumpHD is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package dumphd.util;

import java.io.File;
import java.io.FilenameFilter;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

/**
 * Simple FilenameFilter, checks the given filename, the directory is ignored, against its pattern.
 * The output can be inverted. Directories are always accepted, only files will be filtered.
 *
 * @author KenD00
 */
public class SimpleFilenameFilter implements FilenameFilter {

   private Pattern filenamePattern = null;
   private boolean invert = false;

   /**
    * Constructs a SimpleFilenameFilter
    * 
    * @param pattern The regular expression used to check the given filenames
    * @param caseInsensitive If true, the check is performed case insensitive, otherwise not
    * @param invert If invert is true, this object accepts the given filenames if they don't match the pattern
    */
   public SimpleFilenameFilter(String pattern, boolean caseInsensitive, boolean invert) {
      this.invert = invert;
      if (caseInsensitive) {
         filenamePattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
      } else {
         filenamePattern = Pattern.compile(pattern);
      }
   }

   /* (non-Javadoc)
    * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String)
    */
   public boolean accept(File dir, String name) {
      if (new File(dir, name).isDirectory()) {
         return true;
      } else {
         Matcher matcher = filenamePattern.matcher(name);
         return (matcher.matches() ^ invert);
      }
   }

}
