package edu.uprm.walsaip.vte.core.loader;

import javax.swing.filechooser.FileFilter;

import edu.uprm.walsaip.vte.core.ModuleFactory;

import java.io.File;
import java.util.*;
//import static java.lang.System.out;
import static java.lang.System.err;

public class FileLoaderFactory <E extends FileLoader> extends ModuleFactory<E> {

	
	private Map<String,String> extensionMap;

	public FileLoaderFactory() {
		super();
		extensionMap = new HashMap<String,String>();
	}

	public void registerModule(FileLoaderInfo<? extends E> info) {
		
		
		super.registerModule(info);
		
		String[] extList = info.getExtensionList();
		
		for (String ext: extList ) {	
			extensionMap.put(ext,info.getKey());
		}
	}

	public FileFilter getFileFilter() {
		return new FileFilter() {
			public boolean accept(File f) {
				if (f.isDirectory())
					return true;
				else if (f.isFile()) {

					return extensionMap.containsKey(getExtension(f.getName()));
				}
				return false;

			}

			public String getDescription() {
				// TODO Fix getFileFilter...
				return "Supported files";
			}
		};
	}

	public  E getLoader(String filename)  {
		String ext = getExtension(filename);
		if (extensionMap.containsKey(ext)) {

			try {
				return  moduleMap.get(extensionMap.get(ext)).getModuleClass().newInstance();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		} else
			err.println("No loader found for file type: " + ext);
		return null;
	}

	private static String getExtension(String filename) {
		return filename.substring(filename.lastIndexOf('.')+1);
	}

	public Set<String> getSuportedExtensions() {
		return extensionMap.keySet();
	}

	

}
