/*
Copyright 1990-2001 Sun Microsystems, Inc. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial
portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP OR SUN MICROSYSTEMS, INC. BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE EVEN IF
ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


Except as contained in this notice, the names of The Open Group and/or
Sun Microsystems, Inc. shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior
written authorization from The Open Group and/or Sun Microsystems,
Inc., as applicable.


X Window System is a trademark of The Open Group

OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
logo, LBX, X Window System, and Xinerama are trademarks of the Open
Group. All other trademarks and registered trademarks mentioned herein
are the property of their respective owners. No right, title or
interest in or to any trademark, service mark, logo or trade name of
Sun Microsystems, Inc. or its licensors is granted.

*/


package sun.awt.im.iiimp;

import java.io.IOException;
import java.io.EOFException;
import java.util.HashSet;
import java.text.AttributedCharacterIterator.Attribute;

class ProtocolData implements IIIMProtocol {
    int pos;
    int count;
    byte buf[];

    private final static int DATA_BOUNDARY = 4;

    /**
     * Creates a new instance of ProtocolData.
     */
    ProtocolData() {
	buf = new byte[32];
	count = 0;
	pos = 0;
    }

    /**
     * Creates a new instance of ProtocolData with the specified length
     * of the specified byte buffer.
     */
    ProtocolData(byte b[], int start, int len) {
	pos = 0;
	count = len;
	if (len > 0) {
	    buf = new byte[len];
	    System.arraycopy(b, start, buf, 0, len);
	}
    }

    ProtocolData(byte b[], int len) {
	this(b, 0, len);
    }

    ProtocolData(byte b[]) {
        this(b, b.length);
    }

    /**
     * Creates a copy of the specified ProtocolData.  The only unread 
     * buffer will be copied.
     */
    ProtocolData(ProtocolData d) {
	int newVal = d.count - d.pos;
	if (newVal > 0) {
	    byte newValue[] = new byte[newVal];
	    System.arraycopy(d.buf, d.pos, newValue, 0, newVal);
	    buf = newValue;
	}
	count = newVal;
	pos = 0;
    }

    void write(int b) throws IOException {
	ensureCapacity(count + 1);
	buf[count++] = (byte) (b & 0xFF);
    }

    void write2(int b) throws IOException {
	ensureCapacity(count + 2);
	buf[count++] = (byte) ((b >>> 8) & 0xFF);
	buf[count++] = (byte) ((b >>> 0) & 0xFF);
    }

    void write4(int b) throws IOException {
	ensureCapacity(count + 4);
	buf[count++] = (byte) ((b >>> 24) & 0xFF);
	buf[count++] = (byte) ((b >>> 16) & 0xFF);
	buf[count++] = (byte) ((b >>>  8) & 0xFF);
	buf[count++] = (byte) ((b >>>  0) & 0xFF);
    }

    void writeBytes(byte b[]) throws IOException {
	ensureCapacity(count + b.length);
	System.arraycopy(b, 0, buf, count, b.length);
	count += b.length;
    }

    void writeBytes(byte b[], int length) throws IOException {
	ensureCapacity(count + length);
	System.arraycopy(b, 0, buf, count, length);
	count += length;
    }

    void writeString(String utf) throws IOException {
	int utflen = utf.length();
	int len = utflen * 2;

	write2(len);

	int pad = paddings(len + 2);

	ensureCapacity(count + len + pad);

	for (int i = 0 ; i < utflen ; i++) {
	    char c = utf.charAt(i);
	    buf[count++] = (byte) ((c >>  8) & 0xFF);
	    buf[count++] = (byte) ((c >>  0) & 0xFF);
	}

	for (int j = 0; j < pad; j++) {
	    buf[count++] = (byte) 0;
	}
    }

    int read() throws IOException {
	if (pos >= count) {
	    throw new EOFException();
	}
	int ch = (int) (buf[pos++] & 0x000000FF);
	if (ch < 0) {
	    throw new EOFException();
	}
	return ch;
    }

    int read2() throws IOException {
	int ch1 = read();
	int ch2 = read();
	return (ch1 << 8) + (ch2 << 0);
    }

    int read4() throws IOException {
	int ch1 = read();
	int ch2 = read();
	int ch3 = read();
	int ch4 = read();
	return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
    }

    int read(byte b[], int offset, int size) throws IOException {
	if (size <= 0) {
	    return 0;
	}

	int c = read();
	if (c == -1) {
	    return -1;
	}
	b[offset] = (byte) c;

	int i = 1;
	try {
	    for (; i < size ; i++) {
		c = read();
		if (c == -1) {
		    break;
		}
		if (b != null) {
		    b[offset + i] = (byte) c;
		}
	    }
	} catch (IOException ee) {
	}
	return i;
    }

    String readString() throws IOException {
	int len = read2();
	if (len == 0) {
	    // need to read 2 bytes for padding
	    read2();
	    return (String)null;
	}

	int utflen = len / 2;
        char str[] = new char[utflen];
	int i = 0;
	while (i < utflen) {
	    int ch1 = read();
	    int ch2 = read();
	    str[i++] = (char) ((ch1 << 8) + (ch2 << 0));
	}
	int pad = paddings(len + 2);
	for (int j = 0; j < pad; j++) {
	    read();
	}
        return new String(str, 0, utflen);
    }

    AnnotationValue[] readStringAnnotationValues(Attribute attribute)
	throws IOException {
	int size = read4();
	if (size < 4 * 3) {
	    // size must be bigger than start+end+value_size
	    skipBytes(size);
	    return null;
	}
	HashSet hs = new HashSet();
	while (size > 0) {
	    int start = read4();
	    int end = read4();
	    int len = read4();
	    String value = readString();
	    pad();
	    hs.add(new AnnotationValue(start, end, attribute, value));
	}
	Object[] oa = hs.toArray();
	AnnotationValue[] ava = new AnnotationValue[oa.length];
	for (int i = 0; i < oa.length; i++) {
	    ava[i] = (AnnotationValue)oa[i];
	}

	return ava;
    }

    AnnotationValue[] readTextAnnotationValues(Attribute attribute)
	throws IOException {
	int size = read4();
	if (size < 4 * 3) { 
	    // size must be bigger than start+end+value_size
	    skipBytes(size);
	    return null;
	}
	HashSet hs = new HashSet();
	while (size > 0) {
	    int start = read4();
	    int end = read4();
	    int len = read4();
	    int feedbackCharLen = read4();
	    StringBuffer sb = new StringBuffer();
	    while (feedbackCharLen > 0) {
		sb.append(read2());
		int sk = read2();
		skipBytes(sk);
	    }
	    String value = sb.toString();
	    pad();
	    hs.add(new AnnotationValue(start, end, attribute, value));
	}
	Object[] oa = hs.toArray();
	AnnotationValue[] ava = new AnnotationValue[oa.length];
	for (int i = 0; i < oa.length; i++) {
	    ava[i] = (AnnotationValue)oa[i];
	}

	return ava;
    }

    void ensureCapacity(int minimumNum) {
	int maxNum = buf.length;
	if (minimumNum > maxNum) {
	    int newNum = (maxNum + 1) * 2;
	    if (minimumNum > newNum) {
		newNum = minimumNum;
	    }
	    byte newValue[] = new byte[newNum];
	    System.arraycopy(buf, 0, newValue, 0, count);
	    buf = newValue;
	}
    }

    final static int paddings(int len) {
	return ((DATA_BOUNDARY -((len) % DATA_BOUNDARY)) % DATA_BOUNDARY);
    }

    void pad() throws IOException {
	int pad = paddings(count);
	int total = count + pad;
	for (int i = count; i < total; i++) {
	    write(0);
	}
    }

    void skipBytes(int skip) {
	int num = (count < (pos + skip)) ? (count - pos) : skip;
	pos += num;
    }

    int available() {
	return (count > pos) ? (count - pos) : 0;
    }
    
    void read(IIIMPInputStream in, int count) {
        try {
            pos = 0;
        
            this.count = count;
        
            buf = new byte[count];
            
            in.readFully(buf);
        } catch(IOException e) {
            debug("e = " + e);
        }
    }
    
    void write(IIIMPOutputStream out) {
        try {
            out.write(buf, 0 , count);
        } catch(IOException e) {
            debug("e = " + e);
        }
    }

    private void debug(String str) {
	if (Manager.DEBUG) {
	    System.err.println(str);
	}
    }
}
