// xmlBlaster/demo/javaclients/PtpReceive.java
import org.jutils.log.LogChannel;
import org.xmlBlaster.util.*;
import org.xmlBlaster.client.*;
import org.xmlBlaster.client.protocol.XmlBlasterConnection;
import org.xmlBlaster.engine.helper.MessageUnit;
import org.xmlBlaster.engine.helper.Destination;
import java.io.*;

/**
 * Connects to xmlBlaster with name 'receiver' and waits for updates. 
 * <p />
 * After the third update (abortCount) it does a System.exit and aborts (without logout)
 * <p />
 * Use this client as a partner for PtpSend.java to play with xmlBlaster
 * <p />
 * Invoke:
 *  <pre>
 *  java PtpReceive
 *
 *  java PtpReceive  -abortCount 3
 *  </pre>
 * @see <a href="http://www.xmlBlaster.org/xmlBlaster/doc/requirements/interface.html" target="others">xmlBlaster interface</a>
 */
//public class PtpReceive
public class PtpReceiveInput
{
   private final String ME = "PtpReceive";
   private XmlBlasterConnection receiver = null;
   private final String receiverName = "receiver";
   private int counter = 0;
   private int abortCount = 3;
	
//   public PtpReceive(final Global glob) {
   public PtpReceiveInput(final Global glob) {
      
      final LogChannel log = glob.getLog(null);
      abortCount = glob.getProperty().get("abortCount", 3);
//      abortCount = 1;
		
      try {

         // setup the receiver client ...
         receiver = new XmlBlasterConnection(glob);

         ConnectQos qos = new ConnectQos(glob, receiverName, "secret");
         ConnectReturnQos conRetQos = receiver.connect(qos, new I_Callback() {
            public String update(String cbSessionId, UpdateKey updateKey, byte[] content, UpdateQos updateQos) {
               //log.info(receiverName, "Receiving asynchronous message '" + updateKey.getOid() + "' in default handler");
               log.info(receiverName, "Receiving asynchronous message '" + updateKey.getOid() + "' in default handler");
               counter++;
// Write content to file
               String file = glob.getProperty().get("file", "");

               if(file.length() > 0)
					{               
               log.info(receiverName, "Message content will be written to " + file);
				   	File outFile = new File(file);
                  try {
                      FileOutputStream outFileStream = new FileOutputStream(outFile);
							 outFileStream.write(content);
							 outFileStream.close();
                      } 
   					catch (IOException e) 
					       {
                      System.err.println(e);
			             }   
               log.info(receiverName, "Finished receiving and writing " + file);
							 
               }
              
				  try
		           {
                  EraseKeyWrapper ek = new EraseKeyWrapper(updateKey.getOid());
                  EraseQosWrapper eq = new EraseQosWrapper();
                  EraseRetQos[] eraseArr = receiver.erase(ek.toXml(), eq.toXml());
                 }
              catch (Exception e) {
                  System.err.println(e.toString());
                 }
               
//               
               if (counter == abortCount)
                  System.exit(-1);
					return "";
				};
           });  // Login to xmlBlaster, default handler for updates

         log.info(receiverName, "Receiver connected to xmlBlaster.");
      }
      catch (XmlBlasterException e) {
         log.error(ME, "Houston, we have a problem: " + e.toString());
      }
      finally {
         // Wait a second for messages to arrive before we logout
         try { Thread.currentThread().sleep(1000); } catch( InterruptedException i) {}
         log.info(ME, "Waiting on messages, aborting after " + abortCount + " messages, or hit a key to exit");
         try { System.in.read(); } catch(java.io.IOException e) {}
         
         if (receiver != null) { receiver.disconnect(new DisconnectQos()); }
      }
   }

   /**
    * Try
    * <pre>
    *   java PtpReceive -help
    * </pre>
    * for usage help
    */
   public static void main(String args[]) {
      Global glob = new Global();
      
      if (glob.init(args) != 0) { // Get help with -help
         XmlBlasterConnection.usage();
         glob.getLog(null).info("PtpReceive", "Example: java PtpReceive -abortCount 3\n");
         System.exit(1);
      }

//      new PtpReceive(glob);
      new PtpReceiveInput(glob);
		
   }
}
