// FormEditorFactory.java
// $Id: FormEditorFactory.java,v 1.4 1997/01/17 11:52:54 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 editor factory.
 * Given any Resource, this factory will lok into its set of registered
 * editors to find one that match the given resource. It will than instantiate
 * it and return an appropriate instanbce of ResourceEditor.
 */

public class FormEditorFactory {
    /**
     * The set of classes we know specific editors for.
     */
    static Hashtable editors = new Hashtable() ;

    static {
	registerEditor("w3c.tools.store.Resource"
		       , "w3c.jigsaw.formedit.GenericResourceEditor") ;
	registerEditor("w3c.jigsaw.resources.ContainerResource"
		       , "w3c.jigsaw.formedit.ContainerResourceEditor");
	registerEditor("w3c.jigsaw.resources.FilteredResource"
		       , "w3c.jigsaw.formedit.FilteredResourceEditor");
    }

    public static synchronized
    void registerEditor(String clsname, String editname) {
	try {
	    Class clssrc = Class.forName(clsname) ;
	    Class clsedt = Class.forName(editname) ;
	    editors.put(clssrc, clsedt);
	} catch (Exception ex) {
	    System.out.println("*** FormResourceEditor: static init failed "
			       + " editor "+editname+" for "+clsname);
	    ex.printStackTrace() ;
	    System.exit(1);
	} catch (Error ex) {
	    System.out.println("*** FormResourceEditor: static init failed "
			       + " editor "+editname+" for "+clsname);
	    ex.printStackTrace() ;
	    System.exit(1);
	}
    }

    public static synchronized
    HTTPResource getEditor(Resource resource) {
	Class cls    = resource.getClass() ;
	Class editor = null ;
	while (cls != null ) {
	    editor = (Class) editors.get(cls) ;
	    if ( editor != null ) {
		try {
		    return (HTTPResource) editor.newInstance() ;
		} catch (Exception ex) {
		    ex.printStackTrace() ;
		    return null ;
		}
	    }
	    cls = cls.getSuperclass() ;
	}
	return null ;
    }

}
