/**
 * @file Echo.java
 * 
 * @author Christos Choutouridis AEM:8997
 * @email  cchoutou@ece.auth.gr
 */
package net.hoo2.auth.vmodem;

/**
 * @class Echo
 * 
 * Class to used for the echo sequence
 */
class Echo {
   static final int ECHO_DURATION_DEFAULT = 240;      /** Default duration for the sequence */
   static final int ECHO_BUFFER_SIZE      = 256;      /** Echo buffer size */
   static final String ECHO_BEGIN         = "PSTART"; /** Begin pattern of the response */
   static final String ECHO_END           = "PSTOP";  /** End pattern of the response */

   private Com          com_;             /** Reference to communication module */
   private Log          log_;             /** Reference to logging module */
   private Transaction  transaction_;     /** A transaction object to used as a buffer for all requests */
   private int          duration_;        /** The desired duration for the session */
   private byte[]       code_;            /** The desired code for the session */

   /**
    * Basic constructor
    * @param com        The Communication module to use
    * @param log        The logging module to use
    * @param code       The code to use
    * @param duration   The duration to use
    */
   Echo (Com com, Log log, byte[] code, int duration) {
      com_        = com;
      log_        = log;
      duration_   = duration;
      // Allocate memory for the response
      transaction_= new Transaction(null, new byte[ECHO_BUFFER_SIZE]);
      code_       = code;
   }

   /**
    * Functionality to drain the response buffer for the welcome message
    * from the server
    * @param code    The code that we will use (for printing, not sending)
    */
   void caption (byte[] code) {
      String line;

      line = "Running ECHO with: " + new String(code);
      log_.write(line, true);

      transaction_ = com_.request (transaction_, null, null, null, false);
      line = new String(transaction_.getResponse());
      log_.out(line);
   }

   /**
    * Main transaction loop. It send requests to server, get the response
    * and log the procedure while doing it.
    */
   void run () {
      long start;
      long now;
      String line;

      start = System.currentTimeMillis();
      do {
         transaction_ = com_.request(transaction_, code_, ECHO_BEGIN.getBytes(), ECHO_END.getBytes(), false);
         line = new String(transaction_.code) + ": "
              + new String(transaction_.getResponse())
              + " Tr= " + (transaction_.arrival - transaction_.departure) + " [msec]";
         log_.write(line);
         now = System.currentTimeMillis();
      } while (now - start < duration_*1000);
   }
   
}
