import org.zeromq.ZMQ;
import java.util.ArrayList;
import java.util.List;

public class PointCloudConcatenator {
    public static void main(String[] args) {
        ZMQ.Context context = ZMQ.context(1);

        // Sockets to receive from 3 sources 
        ZMQ.Socket sub1 = context.socket(ZMQ.SUB);
        ZMQ.Socket sub2 = context.socket(ZMQ.SUB);
        ZMQ.Socket sub3 = context.socket(ZMQ.SUB);

        sub1.connect("tcp://192.168.222.168:5556");
        sub2.connect("tcp://192.168.222.168:5557");
        sub3.connect("tcp://192.168.222.168:5558");

        sub1.subscribe(ZMQ.SUBSCRIPTION_ALL);
        sub2.subscribe(ZMQ.SUBSCRIPTION_ALL);
        sub3.subscribe(ZMQ.SUBSCRIPTION_ALL);

        // Socket to publish concatenated data on 5560
        ZMQ.Socket pub = context.socket(ZMQ.PUB);
        pub.bind("tcp://*:5560");

        System.out.println("Java aggregator started — publishing to port 5560");

        while (true) {
            byte[] msg1 = sub1.recv();
            byte[] msg2 = sub2.recv();
            byte[] msg3 = sub3.recv();

            List<byte[]> all = new ArrayList<>();
            all.add(msg1);
            all.add(msg2);
            all.add(msg3);

            int totalSize = msg1.length + msg2.length + msg3.length;
            byte[] combined = new byte[totalSize];

            int pos = 0;
            for (byte[] part : all) {
                System.arraycopy(part, 0, combined, pos, part.length);
                pos += part.length;
            }

            pub.send(combined);
            System.out.println("Published combined point cloud of size " + combined.length);
        }
    }
}

