// FormHelpRegistry.java
// $Id: FormHelperRegistry.java,v 1.2 1997/01/17 09:52:16 abaird Exp $
// (c) COPYRIGHT MIT and INRIA, 1996.
// Please first read the full copyright statement in file COPYRIGHT.html

package w3c.jigsaw.formedit ;

import java.util.*;

import w3c.tools.store.*;
import w3c.jigsaw.resources.*;

/**
 * The form help registery keeps track of the helper editors.
 */

public class FormHelperRegistry {
    /**
     * Our helpers registery. Maps resource classes to helper classes.
     */
    private static Hashtable helpers = new Hashtable() ;
    

    static {
	registerHelper("w3c.jigsaw.resources.ResourceFilter"
		       , "w3c.jigsaw.formedit.GenericFilterEditor") ;
    }

    /**
     * Register a helper editor for the given class.
     * @param cls The class you wich to define a helper for.
     * @param helper The editor helper (wich must conform to the 
     *    FormEditorHelper interface).
     */

    public static synchronized void registerHelper(String cls, String helper) {
	Class clsptr    = null ;
	Class clshelper = null ;
	// Resolve the classes:
	try {
	    clsptr    = Class.forName(cls) ;
	    clshelper = Class.forName(helper);
	} catch (Exception ex) {
	    ex.printStackTrace() ;
	    System.exit(1) ;
	}
	helpers.put(clsptr, clshelper);
    }

    /**
     * Look for a help object to edit the given resource.
     * @param resource The resource to be edited.
     * @return An initialized FormEditorHelper instance, or 
     *    <strong>null</strong> if none was found.
     */

    public static synchronized 
    FormEditorHelper getHelper(Resource resource) {
	Class cls    = resource.getClass() ;
	Class helper = null ;
	while ( cls != null ) {
	    helper = (Class) helpers.get(cls) ;
	    if ( helper != null ) {
		try {
		    return (FormEditorHelper) helper.newInstance() ;
		} catch (Exception ex) {
		    ex.printStackTrace() ;
		    return null ;
		}
	    }
	    cls = cls.getSuperclass() ;
	}
	return null ;
    }

}
