/********************************************************************
 * Copyright © 2005 VHA. All rights reserved
 ********************************************************************/


package gov.va.med.fw.io.parser;

import gov.va.med.fw.util.InvalidConfigurationException;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Locale;
import java.util.StringTokenizer;

/**
 * FilenameFilter implementation for matching extensions.
 * 
 * Created Feb 17, 2006 1:14:41 PM
 * 
 * @author DNS   BOHMEG
 */
public class WildcardFileFilter implements FilenameFilter {
	String wildcard = null;
	private boolean caseInsensitive; 

	public WildcardFileFilter(String wildcard) {
		this.wildcard = wildcard;
	}

	public WildcardFileFilter(String wildcard, boolean caseInsensitive) {
		this.wildcard = wildcard;
		this.caseInsensitive = caseInsensitive;
	}
	
	/**
     * Accepts the wildcard formats *.ext, foo*, foo*.ext, *foo*
     * 
     * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String)
     */
	public boolean accept(File dir, String name) {
		int firstIndex = wildcard.indexOf('*');
		int lastIndex = wildcard.lastIndexOf('*');
		
		boolean accept = false;
		
		String wildcardToUse = wildcard;
		if(caseInsensitive) {
			name = name.toUpperCase(Locale.ENGLISH);			
			wildcardToUse = wildcard.toUpperCase();
		}
		StringTokenizer st = new StringTokenizer(wildcardToUse, "*");			
		
		// *.ext
        if (firstIndex == 0 && lastIndex == 0)
        {
            accept = name.endsWith(st.nextToken());

        }//foo*
        else if (firstIndex > 0 && firstIndex == lastIndex && st.countTokens() == 1)
        {
            accept = name.startsWith(st.nextToken());

        }//foo*.ext
        else if (firstIndex > 0 && firstIndex == lastIndex && st.countTokens() == 2)
        {
            accept = name.startsWith(st.nextToken()) && name.endsWith(st.nextToken());

        }//*foo*
        else if (firstIndex == 0 && lastIndex > 0 && st.countTokens() == 1)
        {
            accept = name.indexOf(st.nextToken()) != 1;
            
        } else
        {
            throw new InvalidConfigurationException(
                    "Wild card specified for inputFileLocation is not supported: "
                            + wildcard);
        }
        return accept;
	}

	/**
	 * @return Returns the caseInsensitive.
	 */
	public boolean isCaseInsensitive() {
		return caseInsensitive;
	}

	/**
	 * @param caseInsensitive The caseInsensitive to set.
	 */
	public void setCaseInsensitive(boolean caseInsensitive) {
		this.caseInsensitive = caseInsensitive;
	}
}
