package net.cobem.grizzly.communication;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class EventRequest implements Cloneable {
    private Short Header;
    private ChannelBuffer Buffer;

    public EventRequest(Short id, ChannelBuffer buffer) {
        this.Header = id;
        this.Buffer = (buffer == null || buffer.readableBytes() == 0) ? ChannelBuffers.EMPTY_BUFFER : buffer;
    }

    public byte[] readBytes(int Amount) {
        return Buffer.readBytes(Amount).array();
    }

    public int readShort() {
        return ByteBuffer.wrap(readBytes(2)).asShortBuffer().get();
    }

    public ChannelBuffer readFixed() {

        return Buffer.readBytes(readShort());
    }

    public Integer readInt() {
        try {
            return ByteBuffer.wrap(readBytes(4)).asIntBuffer().get();
        } catch (Exception ignored) {
        }
        return 0;
    }

    public String readString() {
        return readFixed().toString(Charset.defaultCharset());
    }

    public boolean readBoolean() {
        return (this.Buffer.readableBytes() > 0 && this.Buffer.readByte() == (char) 1);
    }

    public Short header() {
        return this.Header;
    }

    public String body() {

        String consoleText = Buffer.toString(Charset.defaultCharset());

        for (int i = 0; i < 13; i++) {
            consoleText = consoleText.replace(Character.toString((char) i), "{" + i + "}");
        }

        return consoleText;
    }

    public int length() {
        return Buffer.readableBytes();
    }
}
