package speiger.src.coreengine.utils.io.finders;

import java.io.File;
import java.util.StringJoiner;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import speiger.src.collections.objects.lists.ObjectArrayList;
import speiger.src.collections.objects.lists.ObjectList;
import speiger.src.collections.objects.sets.ObjectOrderedSet;

public class JavaFileFinder implements IFileFinder {
	public static final IFileFinder INSTANCE = new JavaFileFinder();
	
	@Override
	public ObjectList<File> build(int flags, String startPath, ObjectOrderedSet<String> validFormats, String description) {
		JFileChooser file = new JFileChooser(startPath);
		if((flags & FOLDER) != 0) file.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		if((flags & ANY) != 0) file.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		if((flags & MULTI_FILE) != 0) file.setMultiSelectionEnabled(true);
		file.setFileHidingEnabled(false);
		file.setFileFilter(new Filter(description, validFormats));
		if((flags & SAVE) != 0 && file.showSaveDialog(null) == 0) return ObjectArrayList.wrap(sanitize(file.getSelectedFiles(), validFormats.getFirst()));
		else if((flags & SAVE) == 0 && file.showOpenDialog(null) == 0) return ObjectArrayList.wrap(file.getSelectedFiles());
		return new ObjectArrayList<>();
	}
	
	protected File[] sanitize(File[] files, String s) {
		for(int i = 0,m = files.length;i < m;i++) {
			File file = files[i];
			if(file.getName().lastIndexOf(".") == -1) files[i] = new File(file.getParent(), file.getName()+"."+s);
		}
		return files;
	}
	
	private static class Filter extends FileFilter {
		String description;
		ObjectOrderedSet<String> validFormats;
		
		public Filter(String description, ObjectOrderedSet<String> validFormats) {
			StringJoiner joiner = new StringJoiner(", ", " (", ")");
			for(String s : validFormats)
				joiner.add("."+s);
			this.description = description + joiner.toString();
			this.validFormats = validFormats;
		}
		
		@Override
		public boolean accept(File f) {
			if(f.isDirectory()) return true;
			String fileName = f.getName();
			return validFormats.contains(fileName.substring(fileName.lastIndexOf(".") + 1));
		}
		
		@Override
		public String getDescription() { return description; }
	}
}
