/*
 * 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.ByteArrayInputStream;
import java.io.IOException;

import org.msgpack.core.MessagePack;
import org.msgpack.core.MessageUnpacker;

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

public class StreamSerializableObjectReaderImpl<T extends StreamSerializable>
        implements StreamSerializableObjectReader<T> {

    @SuppressWarnings("unchecked")
    @Override
    public T read(byte[] serializedObject, int offset, int length) throws SafeStreamDeserializationException {
        try (MessageUnpacker unpacker =
            MessagePack.newDefaultUnpacker(new ByteArrayInputStream(serializedObject, offset, length))) {
            String className = unpacker.unpackString();

            T deserialisedObject = (T) StreamSerializableUtil.resolveByName(className);
            deserialisedObject.deserialize(unpacker);
            return deserialisedObject;
        } catch (IOException e) {
            throw new SafeStreamDeserializationException(e);
        }
    }

    @Override
    public T read(byte[] serializadObject) throws SafeStreamDeserializationException {
        return read(serializadObject, 0, serializadObject.length);
    }

}
