package code.loader;

import code.loader.except.FileFormatNotSupportException;

/**
 * ModuleLoaderFactory instantiates a ModuleLoader based upon the type of the module file to be loaded (currently one of .class/.txt/.xml)
 * <p/>
 * This class is responsible for
 * <OL>
 * <LI> Creating suitable ModuleLoader based upon module filename's extention. 
 * </OL>
 * <p/>
 *
 * @author Sunita Marathe
 * @since Jul 15, 2005 
 */
public class ModuleLoaderFactory {
    private static ClassModuleLoader classModuleLoader = null;
    private static TxtXMLModuleLoader txtXmlModuleLoader = null;
    /**
     * prevent instance creation.
     */
    private ModuleLoaderFactory () {} ;

    public static ModuleLoader createModuleLoader (String filePath) throws FileFormatNotSupportException {

        int index = filePath.lastIndexOf('.');
        if (index < 0) {
            throw new FileFormatNotSupportException("No extension found in " + filePath);
        }
        String format = filePath.substring(index + 1);
        if (format.equals("class")) {

            if (classModuleLoader == null) {
                classModuleLoader = new ClassModuleLoader ();
            }
            return (ModuleLoader) classModuleLoader;
        } else if (format.equals("txt") || format.equals("xml")) {
            if (txtXmlModuleLoader == null) {
                txtXmlModuleLoader = new TxtXMLModuleLoader ();
            }
            // We have desupported XML format for the time being - 7/28/04 Sergio.
            // Hence we raise this exception.
            return (ModuleLoader) txtXmlModuleLoader;
        } else {
            throw new FileFormatNotSupportException("Extension " + format + " of " + filePath + " NOT supported");
        }
    }
}
