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

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.swing.filechooser.FileFilter;

import edu.uprm.walsaip.vte.core.loader.FileLoaderFactory;
import edu.uprm.walsaip.vte.core.loader.FileLoaderInfo;


public class ImageFileLoaderFactory {

	private static FileLoaderFactory<ImageFileLoader> factoryImpl = new FileLoaderFactory<ImageFileLoader>();

	static {
		// TODO Use property/configuration file or reflection for registering
		// modules
		ImageFileLoaderFactory.registerModule(ImageIOFileLoader.MODULE_INFO);
		ImageFileLoaderFactory.registerModule(EnviImageFileLoader.MODULE_INFO);

	}

	public static void registerModule(
			FileLoaderInfo<? extends ImageFileLoader> info) {
		factoryImpl.registerModule(info);
	}

	public static FileFilter getFileFilter() {
		return factoryImpl.getFileFilter();
	}

	public static ImageFileLoader getLoader(String filename) {
		return factoryImpl.getLoader(filename);
	}

	public static Set<String> getSuportedExtensions() {
		return factoryImpl.getSuportedExtensions();
	}

	public static List<String> findSupportedImageFile(String filepath) {
		File file = new File(filepath);
		String basepath = file.getParent(); 
		String filename = file.getName();
		String name = filename.substring(0,filename.lastIndexOf('.') + 1);
		
		if(name.endsWith("_dem.")) {
			return findSupportedImages(basepath,name.substring(0, name.length()-5)+"_texture.");		
		}
		else {
			return findSupportedImages(basepath+File.separator+"textures"+File.separator,name);
		}

	}
	
	private static List<String> findSupportedImages(String basepath,String name) {

		List<String> supportedImages = new ArrayList<String>();
		String imageFilename;
				

		for (String extension : factoryImpl.getSuportedExtensions()) {
			imageFilename = basepath +File.separator+name+extension;
			
			if (new File(imageFilename).exists())
				supportedImages.add(imageFilename);
		}
		return supportedImages;
	}

}
