/*
 * 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.messaging;

import static java.util.Arrays.copyOf;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;

import java.io.IOException;
import java.util.UUID;

import org.junit.Test;

import com.scytl.products.ov.commons.dto.ChoiceCodeGenerationDTO;
import com.scytl.products.ov.commons.safestream.StreamSerializableObjectWriterImpl;

/**
 * Tests of {@link CodecImpl}.
 */
public class CodecImplTest {

    @Test(expected = InvalidMessageException.class)
    public void testDecodeInvalidContent()
            throws IOException, InvalidMessageException {
        ChoiceCodeGenerationDTO<String> message =
            new ChoiceCodeGenerationDTO<String>(new UUID(1, 1),
                "requestId", "payload");
        byte[] bytes =
            new StreamSerializableObjectWriterImpl().write(message);
        bytes = copyOf(bytes, bytes.length - 1);
        CodecImpl.getInstance().decode(bytes);
    }

    @Test(expected = InvalidMessageException.class)
    public void testDecodeInvalidContentType()
            throws InvalidMessageException {
        CodecImpl.getInstance().decode(new byte[] {2 });

    }

    @Test(expected = InvalidMessageException.class)
    public void testDecodeNoContentType() throws InvalidMessageException {
        CodecImpl.getInstance().decode(new byte[0]);

    }

    @Test
    public void testEncodeDecodeBinary() throws InvalidMessageException {
        byte[] message = {1, 2, 3 };
        byte[] bytes = CodecImpl.getInstance().encode(message);
        assertArrayEquals(message,
            (byte[]) CodecImpl.getInstance().decode(bytes));
    }

    @Test
    public void testEncodeDecodeStreamSerializable()
            throws IOException, InvalidMessageException {
        ChoiceCodeGenerationDTO<String> message =
            new ChoiceCodeGenerationDTO<String>(new UUID(1, 1),
                "requestId", "payload");
        byte[] bytes = CodecImpl.getInstance().encode(message);
        @SuppressWarnings("unchecked")
        ChoiceCodeGenerationDTO<String> message2 =
            (ChoiceCodeGenerationDTO<String>) CodecImpl.getInstance()
                .decode(bytes);
        assertEquals(message.getCorrelationId(),
            message2.getCorrelationId());
        assertEquals(message.getRequestId(), message2.getRequestId());
        assertEquals(message.getPayload(), message2.getPayload());
    }

    @Test(expected = InvalidMessageException.class)
    public void testEncodeInvalid() throws InvalidMessageException {
        CodecImpl.getInstance().encode("Invalid");
    }
}
