// SapAttributes.java
// $Id: SapAttributes.java,v 1.2 1998/01/22 14:40:25 bmahe Exp $
// (c) COPYRIGHT MIT and INRIA, 1996.
// Please first read the full copyright statement in file COPYRIGHT.html

package org.w3c.www.sap;

import java.util.*;

/**
 * A private class to handle SAP attributes.
 */

class SapAttributes {
    private static final String zeroarray[] = new String[0];

    Hashtable attrs = null;

    /**
     * Dump that set of SAP attributes into the given StringBuffer.
     * @param sb The StringBuffer to dump these attributes to.
     */

    void dump(StringBuffer sb) {
	if ( attrs == null )
	    return;
	Enumeration e = attrs.keys();
	while ( e.hasMoreElements() ) {
	    String k   = (String) e.nextElement();
	    String v[] = (String[]) attrs.get(k);
	    if ( v.length == 0 ) {
		sb.append("a="); 
		sb.append(k); 
		sb.append('\n');
	    } else {
		for (int i = 0 ; i < v.length ; i++) { 
		    sb.append("a=");
		    sb.append(k); 
		    sb.append(':'); 
		    sb.append(v[i]); 
		    sb.append('\n');
		}
	    }
	}
    }

    /**
     * Add a binding to the given attribute.
     * @param key The attribute name.
     * @param value The other attribute value.
     */

    void addAttribute(String key, String value) {
	String vals[] = null;
	// Create hashtable or fetch prev values:
	if ( attrs == null ) {
	    attrs = new Hashtable(11);
	} else {
	    vals = (String[]) attrs.get(key);
	}
	// Add extra value:
	if ( vals != null ) {
	    String nvals[] = new String[vals.length+1];
	    System.arraycopy(vals, 0, nvals, 0, vals.length);
	    nvals[vals.length] = value;
	    vals = nvals;
	} else {
	    vals = new String[1];
	    vals[0] = value;
	}
	attrs.put(key, vals);
    }

    /**
     * Add a flag attribute.
     * @param key The flag name.
     */

    void addFlag(String key) {
	if ( attrs == null )
	    attrs = new Hashtable(11);
	attrs.put(key, zeroarray);
    }


    /**
     * Get all mapping for that attribute.
     * @param key The attribute to fetch.
     * @return A String array, or <strong>null</strong>.
     */
	
    String[] getValues(String key) {
	return ((attrs != null) ? (String[]) attrs.get(key) : null);
    }

    /**
     * Get the first mapping for that attribute.
     * @param key The attribute to fetch.
     * @return A String instance, or <strong>null</strong>.
     */

    String getValue(String key) {
	if ( attrs != null ) {
	    String vals[] = (String[]) attrs.get(key);
	    return (( vals != null )
		    ? ((vals.length == 0) ? "" : vals[0])
		    : null);
	} else {
	    return null;
	}
    }

    /**
     * Remove all settings of an attribute.
     * @param key The attribute name.
     */

    public void removeAttribute(String key) {
	if ( attrs != null )
	    attrs.remove(key);
    }

    SapAttributes() {
    }

}
