// GenericFilterEditor.java
// $Id: GenericFilterEditor.java,v 1.6 1997/03/28 16:12:23 abaird Exp $
// (c) COPYRIGHT MIT and INRIA, 1996.
// Please first read the full copyright statement in file COPYRIGHT.html

package w3c.jigsaw.formedit ;

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

class FilterAttributeHandler extends FormCardHandler {
    ResourceFilter      filter = null ;
    GenericFilterEditor editor = null ;
    boolean             done   = false ;
    FormCardResource    card   = null;
    String              reloc  = null;

    public void notifyBeginProcessing(FormCardResource c, Request r) {
	reloc = null;
    }

    public String notifyEndProcessing(FormCardResource c, Request r) {
	return reloc;
    }

    public void notifyButtonClick(String label) {
	if ( label.equals("Remove") ) {
	    done = true ;
	    editor.removeFilter(filter) ;
	}
    }

    public void notifyChange(FormFieldInterface field, Object value) 
	throws FormFieldException
    {
	if ( field.getName().equals("identifier") ) {
	    // Rename the card links:
	    editor.form.renameCard(editor.target.getIdentifier()
				   , (String) value);
	    editor.form.renameCard("("+editor.target.getIdentifier()+")"
				   , "(" + (String) value + ")");
	    reloc = (String) value;
	}
	filter.setValue(field.getName(), value) ;
    }

    FilterAttributeHandler(GenericFilterEditor editor, ResourceFilter filter) {
	this.editor = editor ;
	this.filter = filter ;
    }
}

public class GenericFilterEditor implements FormEditorHelper {
    ResourceFilter target = null ;
    FormResource   form   = null ;

    public void removeFilter (ResourceFilter filter) {
	FilteredResource r = (FilteredResource) filter.getTargetResource();
	r.unregisterFilter(filter) ;
	form.removeFormCard(filter.getIdentifier()) ;
	form.removeFormCard("("+filter.getIdentifier()+")");
    }

    public void generateFormCard(Resource target, FormResource form) {
	FormCardResource   card  = null ;
	FormFieldInterface field = null ;

	this.target = (ResourceFilter) target ;
	this.form   = form ;
	// Generate the card for the filter's attribute:
	Class            cls     = target.getClass() ;
	Attribute        attrs[] = AttributeRegistry.getClassAttributes(cls) ;
	FilterAttributeHandler h = null;
	h = new FilterAttributeHandler(this, this.target);
	card    = form.defineCard(h
				  , target.getIdentifier()
				  , target.getIdentifier()) ;
	h.card = card;
	for (int i = 0 ; i < attrs.length ; i++) {
	    Attribute a = attrs[i] ;
	    if ( ! a.checkFlag(Attribute.EDITABLE) )
		continue ;
	    field = FormFieldRegistry.getField(target, attrs[i]);
	    if ( field != null ) 
		card.addField(field) ;
	}
	card.addButton("Remove") ;
    }

}
