package input;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;

public class FileFilter {
	/**
	 * Search for files none recursively.
	 * 
	 * @param path Starting folder.
	 * @param startswith File names are accepted if they start with this pattern.
	 * @param endswith File names are accepted if they end with this pattern.
	 * @return An array of files with the specified pattern.
	 */
	public static File[] listFiles(final String path, final String startswith, final String endswith) {
		assert path != null && path.length() > 0;
		File directory = path.endsWith("/") ? new File(path) : new File(path + "/"); 
		File[] entries = null;
		
		boolean st = startswith != null && startswith.length() > 0;
		boolean en = endswith != null && endswith.length() > 0;
		if(st && en) {
			// Are there some "startswith*.endswith" files?
			entries = directory.listFiles(new FilenameFilter() {
				@Override
				public boolean accept(File entry, String name) {
					return name.startsWith(startswith) && name.endsWith(endswith);
				}
			});
		}
		else if(st) {
			// Are there some "startswith*" files?
			entries = directory.listFiles(new FilenameFilter() {
				@Override
				public boolean accept(File entry, String name) {
					return name.startsWith(startswith);
				}
			});
		}
		else if(en) {
			// Are there some "*endswith" files?
			entries = directory.listFiles(new FilenameFilter() {
				@Override
				public boolean accept(File entry, String name) {
					return name.endsWith(startswith);
				}
			});
		}
		else {
			// Are there some files?
			entries = directory.listFiles(new FilenameFilter() {
				@Override
				public boolean accept(File entry, String name) {
					String ln = name.toLowerCase();
					if(ln.endsWith(".png"))
						return true;
					if(ln.endsWith(".jpg"))
						return true;
					if(ln.endsWith(".jpeg"))
						return true;
					return false;
				}
			});
		}
		Arrays.sort(entries);
		return entries;
	}

}
