/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.activeblaze.wire;

import java.io.DataOutput;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UTFDataFormatException;

/**
 * Very similar to the java.io.ByteArrayOutputStream but this version is not
 * thread safe and the resulting data is returned in a Buffer to avoid an extra
 * byte[] allocation.
 */
final public class BufferOutputStream extends OutputStream implements DataOutput {
    private byte writeBuffer[] = new byte[8];
    private byte buffer[];
    private int offset;
    private int pos;

    public BufferOutputStream(int size) {
        this(new byte[size]);
    }

    public BufferOutputStream(byte[] buffer) {
        this.buffer = buffer;
    }

    public BufferOutputStream(Buffer data) {
        this.buffer = data.data;
        this.pos = this.offset = data.offset;
    }

    /**
     * Get the buffer
     *
     * @return the buffer
     */
    public byte[] getBuffer() {
        return this.buffer;
    }

    /**
     * Get the offset
     *
     * @return the offset
     */
    public int getOffset() {
        return this.offset;
    }

    /**
     * Get the pos
     *
     * @return the pos
     */
    public int getPos() {
        return this.pos;
    }

    public void skip(int skip) {
        int newPos = this.pos + skip;
        checkCapacity(newPos);
        this.pos = newPos;
    }

    public void position(int pos) {
        int newPos = this.offset + pos;
        checkCapacity(newPos);
        this.pos = newPos;
    }

    public void write(int b) {
        int newPos = this.pos + 1;
        checkCapacity(newPos);
        this.buffer[this.pos] = (byte) b;
        this.pos = newPos;
    }

    public void write(byte b[], int off, int len) {
        int newPos = this.pos + len;
        checkCapacity(newPos);
        System.arraycopy(b, off, this.buffer, this.pos, len);
        this.pos = newPos;
    }

    public void write(Buffer buffer) {
        if (buffer != null) {
            writeInt(buffer.length);
            write(buffer.data, buffer.offset, buffer.length);
        } else {
            writeInt(0);
        }
    }

    public void writeObject(Object object) throws IOException {
        IOUtils.writeObject(this, object);
    }

    public void reset() {
        this.pos = this.offset;
    }

    public Buffer toBuffer() {
        return new Buffer(this.buffer, this.offset, this.pos);
    }

    public byte[] toByteArray() {
        return toBuffer().toByteArray();
    }

    public int length() {
        return pos - offset;
    }

    public void write(byte[] b) {
        write(b, 0, b.length);
    }

    public void writeBoolean(boolean v) {
        write(v ? 1 : 0);
    }

    public void writeByte(int v) {
        write(v);
    }

    public void writeBytes(String s) {
        int len = s.length();
        for (int i = 0; i < len; i++) {
            write((byte) s.charAt(i));
        }
    }

    public void writeString(String s) {
        if (s == null) {
            writeShort(0);
        } else {
            int len = s.length();
            writeShort(len);
            for (int i = 0; i < len; i++) {
                write((byte) s.charAt(i));
            }
        }
    }

    public void writeChar(int v) {
        write((v >>> 8) & 0xFF);
        write((v >>> 0) & 0xFF);
    }

    public void writeChars(String s) {
        int len = s.length();
        for (int i = 0; i < len; i++) {
            int v = s.charAt(i);
            write((v >>> 8) & 0xFF);
            write((v >>> 0) & 0xFF);
        }
    }

    public void writeDouble(double v) {
        writeLong(Double.doubleToLongBits(v));
    }

    public void writeFloat(float v) {
        writeInt(Float.floatToIntBits(v));
    }

    public void writeInt(int v) {
        write((v >>> 24) & 0xFF);
        write((v >>> 16) & 0xFF);
        write((v >>> 8) & 0xFF);
        write((v >>> 0) & 0xFF);
    }

    /**
     * @see java.io.DataOutput#writeLong(long)
     */
    public void writeLong(long v) {
        writeBuffer[0] = (byte) (v >>> 56);
        writeBuffer[1] = (byte) (v >>> 48);
        writeBuffer[2] = (byte) (v >>> 40);
        writeBuffer[3] = (byte) (v >>> 32);
        writeBuffer[4] = (byte) (v >>> 24);
        writeBuffer[5] = (byte) (v >>> 16);
        writeBuffer[6] = (byte) (v >>> 8);
        writeBuffer[7] = (byte) (v >>> 0);
        write(writeBuffer, 0, 8);
    }

    public void writeShort(int v) {
        write((v >>> 8) & 0xFF);
        write((v >>> 0) & 0xFF);
    }

    public void writeUTF(String str) throws IOException {
        int strlen = str.length();
        int utflen = 0;
        int c, count = 0;
        /* use charAt instead of copying String to char array */
        for (int i = 0; i < strlen; i++) {
            c = str.charAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) {
                utflen++;
            } else if (c > 0x07FF) {
                utflen += 3;
            } else {
                utflen += 2;
            }
        }
        if (utflen > 65535)
            throw new UTFDataFormatException("encoded string too long: " + utflen + " bytes");
        byte[] bytearr = null;
        bytearr = new byte[utflen + 2];
        bytearr[count++] = (byte) ((utflen >>> 8) & 0xFF);
        bytearr[count++] = (byte) ((utflen >>> 0) & 0xFF);
        int i = 0;
        for (i = 0; i < strlen; i++) {
            c = str.charAt(i);
            if (!((c >= 0x0001) && (c <= 0x007F)))
                break;
            bytearr[count++] = (byte) c;
        }
        for (; i < strlen; i++) {
            c = str.charAt(i);
            if ((c >= 0x0001) && (c <= 0x007F)) {
                bytearr[count++] = (byte) c;
            } else if (c > 0x07FF) {
                bytearr[count++] = (byte) (0xE0 | ((c >> 12) & 0x0F));
                bytearr[count++] = (byte) (0x80 | ((c >> 6) & 0x3F));
                bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F));
            } else {
                bytearr[count++] = (byte) (0xC0 | ((c >> 6) & 0x1F));
                bytearr[count++] = (byte) (0x80 | ((c >> 0) & 0x3F));
            }
        }
        write(bytearr, 0, utflen + 2);
    }

    private final void checkCapacity(int minimumCapacity) {
        if (minimumCapacity > this.buffer.length) {
            byte b[] = new byte[Math.max(this.buffer.length << 1, minimumCapacity)];
            System.arraycopy(this.buffer, 0, b, 0, this.buffer.length);
            this.buffer = b;
        }
    }
}
