package org.yamcs.hornetq;

import org.hornetq.api.core.HornetQException;
import org.hornetq.api.core.SimpleString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yamcs.api.Protocol;
import org.yamcs.api.YamcsClient;
import org.yamcs.api.YamcsSession;
import org.yamcs.archive.IndexRequestListener;
import org.yamcs.protobuf.Yamcs.IndexResult;
import org.yamcs.protobuf.Yamcs.ProtoDataType;

public class HornetQIndexRequestListener implements IndexRequestListener {
    
    static Logger log=LoggerFactory.getLogger(HornetQIndexRequestListener.class);
    SimpleString dataAddress;
    YamcsSession yamcsSession;
    YamcsClient yamcsClient;
    private boolean first;
    
    public HornetQIndexRequestListener(SimpleString replyto) {
        this.dataAddress = replyto;
        first = true;
    }
    
    @Override
    public void processData(IndexResult indexResult) throws Exception {
        if (first) {
            yamcsSession=YamcsSession.newBuilder().build();
            yamcsClient=yamcsSession.newClientBuilder().setRpc(false).setDataProducer(true).build();
            Protocol.killProducerOnConsumerClosed(yamcsClient.dataProducer, dataAddress);
            first = false;
        }
        yamcsClient.sendData(dataAddress, ProtoDataType.ARCHIVE_INDEX, indexResult);
    }

    @Override
    public void finished(boolean success) {
        if (success) {
            try {
                yamcsClient.sendDataEnd(dataAddress);
            } catch (Exception e) {
                log.error("got exception while sending the response", e);
            }
        }
        try {
            if (yamcsClient != null) yamcsClient.close();
        } catch (HornetQException e) {
            log.warn("Got exception while closing client", e);
        }
        try {
            if( yamcsSession != null ) yamcsSession.close();
        } catch (HornetQException e) {
            log.warn("Got exception while closing client", e);
        }
    }
}

@@ -925,32 +925,219 @@
 f (first) %7B%0A    
+        createYamcsClient();%0A        %7D%0A        yamcsClient.sendData(dataAddress, ProtoDataType.ARCHIVE_INDEX, indexResult);%0A    %7D%0A%0A    private void createYamcsClient() throws Exception %7B%0A
         yamcsSes
@@ -1176,36 +1176,32 @@
 uild();%0A        
-  
-  
 yamcsClient=yamc
@@ -1269,28 +1269,24 @@
 e).build();%0A
-    
         Prot
@@ -1363,28 +1363,24 @@
 s);%0A        
-    
 first = fals
@@ -1390,105 +1390,14 @@
     
-  
-  
 %7D%0A    
-    yamcsClient.sendData(dataAddress, ProtoDataType.ARCHIVE_INDEX, indexResult);%0A    %7D%0A
 %0A   
@@ -1484,32 +1484,120 @@
           try %7B%0A
+                if (first) %7B%0A                    createYamcsClient();%0A                %7D%0A
                 

fix NPE when there is no index record