package org.gnunet.construct;

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

/**
 * ...
 *
 * @author Florian Dold
 */
public class OptionalUnionTest {
    public interface TestUnion extends MessageUnion {}
    @UnionCase(1)
    public static class UnionMember1 implements TestUnion {
        @ZeroTerminatedString
        public String str;
    }
    @UnionCase(2)
    public static class UnionMember2 implements TestUnion {
        @Int32
        public int i;
    }

    public static class OptionalUnionMessage implements Message {
        @FrameSize
        @UInt32
        public int size;
        @UInt32
        public int tag;
        @Union(tag = "tag", optional = true)
        public TestUnion x;
    }

    public void setupMessageMap() {
        MessageLoader.registerUnionCase(TestUnion.class, UnionMember1.class, 1);
        MessageLoader.registerUnionCase(TestUnion.class, UnionMember2.class, 2);
    }

    @Test
    public void test_optional_union1() {
        setupMessageMap();

        OptionalUnionMessage m = new OptionalUnionMessage();
        UnionMember1 u1 = new UnionMember1();
        u1.str = "foo";
        m.x = u1;

        Construct.patch(m);
        byte[] data = Construct.toBinary(m);

        System.out.println(data.length);

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

        Assert.assertNotNull(m2.x);
    }

    @Test
    public void test_optional_union2() {
        setupMessageMap();

        OptionalUnionMessage m = new OptionalUnionMessage();

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

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

        Assert.assertNull(m2.x);

    }
}
