/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.commons.safestream;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.msgpack.core.MessagePack;
import org.msgpack.core.MessagePacker;

import com.scytl.products.ov.commons.beans.domain.model.messaging.StreamSerializable;

public class StreamSerializableObjectWriterImpl implements StreamSerializableObjectWriter {

    @Override
    public byte[] write(StreamSerializable streamSerializableObject, int offset) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        for (int i = 0; i < offset; i++) {
            out.write(0);
        }
        try (MessagePacker packer = MessagePack.newDefaultPacker(out)) {
            packer.packString(streamSerializableObject.type().name());
            streamSerializableObject.serialize(packer);
            packer.close();
        }
        return out.toByteArray();
    }
    
    @Override
    public byte[] write(StreamSerializable streamSerializableObject) throws IOException {
        return write(streamSerializableObject, 0);
    }
}
