package org.jcon.df.edit.module;

import org.jcon.df.edit.EditListener;
import org.jcon.param.Param;
import org.jcon.util.GenLib;
import java.awt.*;
import java.util.Hashtable;

/**
 * Creates Modules on request, thus encapsulating the
 * actual class used to implement the Module interface.
 * All static methods.
 *
 * @author Jack Harich
 */
public class ModuleFactory {

//---------- Private Fields ------------------------------
// Key = type, Object = Module
// Could use ModuleCreator as Object but that's extra classes
private static Hashtable moduleTypes = new Hashtable();

//---------- Initialization ------------------------------
// Add more here as needed
static {
    String prefix = "org.jcon.df.edit.module.";
    addType("CardPanel",     prefix + "CardPanel");
    addType("BorderPanel",   prefix + "BorderPanel");
    addType("EditButtonBar", prefix + "EditButtonBar");
    addType("MoveButtonBar", prefix + "MoveButtonBar");
    addType("RowFieldPanel", prefix + "RowFieldPanel");
    addType("RowListPanel",  prefix + "RowListPanel");
    addType("StackedBorderLayoutPanel",  prefix + "StackedBorderLayoutPanel");
    addType("TabPanel",      prefix + "TabPanel");
}
//---------- Public Methods ------------------------------
/**
 * Adds the module type. The type must be unique per factory.
 * This method allows third party classes to add additional
 * types easily.
 * <p>
 * The type is the "logical type" for the module. We map to
 * a className to allow easily changing the actual class
 * used for a type. This could not be done if the class name
 * was in the Param.
 */
public static void addType(String type, String className) {
    if (moduleTypes.containsKey(type)) {
        throw new IllegalArgumentException("The type '" +
            type + "' has already been added.");
    } else {
        moduleTypes.put(type, className);
    }
}
public static Module createModule(String name, Param param) {
    // Get moduleType for type in param
    String type = param.getString("Type");
    String className = (String)moduleTypes.get(type);
    if (className == null) {
        IllegalArgumentException ex = new IllegalArgumentException(
            "Unknown type '" + type + "'.");
        GenLib.exception("ModuleFactory.createModule()",
            ex.getMessage(), ex);
        throw ex;
    }
    // Create and configure module
    Module module = (Module)GenLib.createInstance(className);
    // May add name property in future
    module.setName(name);

    return module;
}
//---------- Private Methods -----------------------------
//--- Std
private static void print(String text) {
    System.out.println("ModuleFactory" + text);
}

} // End class
