// AdminProtocol writer
package w3c.jigsaw.admin;

import java.io.*;

import w3c.www.mime.*;
import w3c.jigsaw.daemon.*;
import w3c.tools.store.*;
import w3c.jigsaw.resources.*;

class AdminWriter {

    /**
     * Get the number of bytes when encoding String in UTF7.
     * @param str The String that is to be written.
     * @return The number of bytes.
     */

    protected final int getUTFLength(String str) {
	int    strlen = str.length() ;
	int    utflen = 0 ;

	for (int i = 0 ; i < strlen ; i++) {
	    int c = str.charAt(i);
	    if ((c >= 0x0001) && (c <= 0x007F)) {
		utflen++;
	    } else if (c > 0x07FF) {
		utflen += 3;
	    } else {
		utflen += 2;
	    }
	}
	return utflen + 2 ;
    }


    /**
     * Write the given resource to the given output stream.
     * @param out The object output stream to write to.
     * @param resource The resource to write
     * @return The number of bytes wriiten out to the wire.
     * @exception IOException If something went wrong.
     */

    protected final int writeResource(DataOutputStream out
				      , Resource resource) 
	throws IOException
    {
	int wrote = 0;
	// Write the class hierarchy of that resource:
	for (Class c = resource.getClass(); c != null; c = c.getSuperclass()) {
	    wrote += getUTFLength(c.getName());
	    out.writeUTF(c.getName());
	}
	out.writeUTF("");
	wrote += getUTFLength("");
	// Return the total number of emitted bytes:
	return wrote;
    }

    /**
     * Write that set of attributes to the given output stream.
     * @param out The object output stream to write to.
     * @param attrs The attributes to write.
     * @exception IOException If some IO error occurs.
     */

    protected int writeAttributes(DataOutputStream out
				  , Attribute attrs[]) 
	throws IOException
    {
	ByteArrayOutputStream bytes = new ByteArrayOutputStream();
	ObjectOutputStream    oout  = new ObjectOutputStream(bytes);

	Attribute ca[] = new Attribute[attrs.length];
	for (int i = 0; i < ca.length ; i++) {
	    if ( attrs[i].checkFlag(Attribute.DONTSAVE) )
		continue;
	    ca[i] = attrs[i];
	}
	oout.writeObject(ca);
	oout.close();
	byte bits[] = bytes.toByteArray(); 
	out.write(bits);
	return bits.length;
    }

    AdminWriter(ServerHandler server) {
    }

}
