package org.gnunet.construct;

import org.junit.Assert;
import org.junit.Test;

import java.util.Random;

/**
 * Miscellaneous tests for org.gnunet.construct.
 *
 * @author Florian Dold
 */
public class ConstructTest {
    public static class ByteFillTestMessage implements Message {
        @FrameSize
        @UInt32
        public int frameSize;
        @FillWith @UInt8
        public byte[] bytes;
    }

    public static class BoolTestMessage implements Message {
        @UInt32
        public boolean x1;
        @Int16
        public boolean x2;
    }

    @Test
    public void test_bool_conversion() {
        BoolTestMessage m = new BoolTestMessage();
        m.x1 = true;
        m.x2 = true;
        byte[] bin = Construct.toBinary(m);
        BoolTestMessage m2 = Construct.parseAs(bin, BoolTestMessage.class);
        Assert.assertEquals(m.x1, m2.x1);
        Assert.assertEquals(m.x2, m2.x2);
    }

    @Test
    public void test_ByteFill() {
        ByteFillTestMessage msg = new ByteFillTestMessage();
        msg.bytes = new byte[]{0,1,2,3};
        Construct.patch(msg);
        byte[] bin = Construct.toBinary(msg);

        ByteFillTestMessage msg_r = Construct.parseAs(bin, ByteFillTestMessage.class);

        Assert.assertArrayEquals(new byte[]{0,1,2,3}, msg_r.bytes);
    }


    @Test
    public void test_IntMessage() {
        IntMessage im = new IntMessage();
        Random r = new Random();
        im.i1 = r.nextLong();
        im.i2 = r.nextLong();
        im.i3 = r.nextLong();
        im.i4 = r.nextLong();
        im.i5 = r.nextLong();
        im.i6 = r.nextLong();
        im.i7 = r.nextLong();
        im.i8 = r.nextLong();

        byte[] data = Construct.toBinary(im);

        Construct.parseAs(data, IntMessage.class);

        Assert.assertEquals((1+2+4+8)*2, data.length);
        Assert.assertEquals((1+2+4+8)*2, Construct.getStaticSize(im));
    }

    @Test(expected = AssertionError.class)
    public void test_PrivateMemberMessage() {
        PrivateMemberMessage m1 = new PrivateMemberMessage();
        byte[] data = Construct.toBinary(m1);
        Construct.parseAs(data, PrivateMemberMessage.class);
    }


    @Test
    public void test_variable_size() {
        VariableSizeMessage m1 = new VariableSizeMessage();
        m1.n1 = 2;
        m1.n2 = 3;
        m1.a1 = new int[]{42,43};
        m1.a2 = new int[]{1,2,1000};

        byte[] data = Construct.toBinary(m1);

        VariableSizeMessage m2 = Construct.parseAs(data, VariableSizeMessage.class);

        Assert.assertEquals(m1.n1, m2.n1);
        Assert.assertEquals(m1.n2, m2.n2);
        Assert.assertArrayEquals(m1.a1, m2.a1);
        Assert.assertArrayEquals(m1.a2, m2.a2);
    }


}

