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

/** @name imports */
/** @{ */
import java.io.IOException;
import java.io.PrintWriter;
/** @} */

/**
 * @class Log
 * 
 * A common log functionality class for all sessions
 */
class Log {

   private String      logfile_;    /** The log file name */
   private boolean     verbose_;    /** The desired verbosity (for the console)*/
   private PrintWriter writer_;     /** A buffered writer to use for streaming */

   /**
    * Basic constructor
    * @param logfile    The log filename
    * @param verbose    The desired verbosity (for the console)
    */
   Log (String logfile, boolean verbose) {
      logfile_ = logfile;
      verbose_ = verbose;
   }

   /**
    * Try to open the log file
    * @return  The status of the operation
    */
   boolean open () {
      if (logfile_ != null) {
         try {
            writer_ = new PrintWriter(logfile_);
         }
         catch (IOException exp) {
            System.err.println( "Open log file failed: " + exp.getMessage() );
            return false;
         }
      }
      return true;
   }
   /**
    * Try to open a log file
    * @param logfile    The log file to open
    * @return           The status of the operation
    */
   boolean open (String logfile) {
      logfile_ = logfile;
      return open();
   }

   /**
    * Close the opened file
    * @return     The status of the operation
    */
   boolean close () {
      try {
         if (writer_ != null)
            writer_.close();
      } catch (Exception ex) {
         return false;
      }
      return true;
   }

   /** 
    * Log to file and print to console
    * @param line    The line to log
    * @param out     Console output request flag. If true, echo the line to console
    */
   void write (String line, boolean out) {
      if (logfile_ != null) writer_.println(line);
      if (verbose_ || out)  System.out.println(line);
   }

   /** 
    * Log to file and print to console
    * @param line    The line to log
    */
   void write (String line) {
      if (logfile_ != null) writer_.println(line);
      if (verbose_)         System.out.println(line);
   }

   /**
    * Echo the line to console
    * @param line    The line to print
    */
   void out (String line) {
      if (verbose_)  System.out.println(line);
   }
}
