/*
Copyright (C) 2000-2010  Ministere de la culture et de la communication (France), AJLSM
See LICENCE file
*/
package fr.gouv.culture.sdx.user;

import fr.gouv.culture.sdx.framework.Framework;
import fr.gouv.culture.sdx.pipeline.AbstractTransformation;
import fr.gouv.culture.sdx.utils.constants.Node;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

import java.util.Enumeration;
import java.util.Hashtable;

/**Allows the insertion of Group information
 * within Identity documents.
 */
public class GroupInformationInserter extends AbstractTransformation {

    /** The element for the group. */
    private final static String ELEMENT_GROUP = "group"; //TODO : move to constants ? -pb

    /** The attribute for the name. */
    private static final String ATTRIBUTE_NAME = Node.Name.NAME;

    /** A hashtable of group names. */
    private Hashtable groups;

    /**
     * Creates an inserter for a list of groups.
     *
     * @param   groups      A hashtable of group names.
     * @param   handler     The handler where insert process will take place.
     */
    public GroupInformationInserter(Hashtable groups, ContentHandler handler) {
        this.groups = groups;
        setContentHandler(handler);
    }

    /**
     * Inserts group elements at the end of the document.
     */
    public void endDocument() throws SAXException {
        if (groups != null && contentHandler != null) {
            // Iterate over the keys of the hashtable
            Enumeration gs = groups.keys();
            while (gs.hasMoreElements()) {
                String groupName = (String) gs.nextElement();
                AttributesImpl atts = new AttributesImpl();
                atts.addAttribute("", ATTRIBUTE_NAME, ATTRIBUTE_NAME, Node.Type.CDATA, groupName);
                contentHandler.startElement(Framework.SDXNamespaceURI, ELEMENT_GROUP, Framework.SDXNamespacePrefix + ":" + ELEMENT_GROUP, atts);
                contentHandler.endElement(Framework.SDXNamespaceURI, ELEMENT_GROUP, Framework.SDXNamespacePrefix + ":" + ELEMENT_GROUP);
            }
        }
        super.endDocument();
    }

    /**This object can be configured if necessary. Currently has no function.
     *
     * @param configuration
     * @throws ConfigurationException
     */
    public void configure(Configuration configuration) throws ConfigurationException {
    }
    
    /* (non-Javadoc)
	 * @see fr.gouv.culture.sdx.utils.xml.AbstractSdxXMLPipe#initToSax()
	 */
	protected boolean initToSax() {
		if(!super.initToSax())
			return false;
		else{
			this._xmlizable_objects.put("Name",this.getClass().getName());
			return true;
		}
	}
}
