package com.cnambot.controlServer.protocol;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * Created by orocos on 6/4/15.
 */
@Deprecated
public class ProtocolOutputStream extends FilterOutputStream {

    /**
     * This protocols is simple: Each message is preceded by the payload length
     * (in bytes). The "message length" information itself is 4 bytes-long (an
     * int).
     *
     * Example: if I want to send "aaaa" (4 characterslong), "4aaaa" will be
     * sent. Every string is US-ASCII encoded before being sent.
     *
     */
    public ProtocolOutputStream(OutputStream out) {
        super(out);
    }

    public void writeCommand(String command) throws IOException {
        byte[] payload = command.getBytes(StandardCharsets.US_ASCII);
        int payloadLength = payload.length;

        byte[] header = new byte[ProtocolConstants.HEADER_LENGTH];
        for (int i = 0; i < ProtocolConstants.HEADER_LENGTH; i++) {
            header[i] = (byte) ((payloadLength >> (i * 8)) & 0xFF);
        }

        super.write(header, 0, ProtocolConstants.HEADER_LENGTH);
        super.write(payload, 0, payloadLength);
    }
}
