package util.log;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class LogWriter {
   private String logfile;
   private int state = 0;
   private RandomAccessFile file;
   private boolean closed = false;

   public LogWriter(String logfile) {
      this.logfile = logfile;
   }

   public boolean open() {
      if (this.state == 1) {
         return true;
      } else {
         try {
            String dir = "";

            try {
               dir = LogConfig.getDirectory();
               if (dir != null && !dir.endsWith("/")) {
                  dir = dir + "/";
                  File directory = new File(dir);
                  if (!directory.exists()) {
                     try {
                        directory.mkdirs();
                     } catch (Exception ex) {
                        SQLLogger.log(ex.getMessage());
                     }
                  }
               }

               if (dir == null) {
                  dir = "";
               }
            } catch (Exception ex) {
               SQLLogger.log(ex.getMessage());
            }

            this.state = 1;
            this.file = new RandomAccessFile(dir + this.logfile, "rw");
            this.file.seek(this.file.length());
            return true;
         } catch (Exception e) {
            SQLLogger.log(e.getMessage());
            return false;
         }
      }
   }

   public boolean write(byte[] buffer) {
      try {
         this.file.write(buffer);
         return true;
      } catch (Exception e) {
         SQLLogger.log(e.getMessage());
         return false;
      }
   }

   public void close() {
      try {
         this.state = -1;
         this.closed = true;
         this.file.close();
      } catch (IOException e) {
         SQLLogger.log(e.getMessage());
      }

   }

   public void flush() {
      if (this.closed) {
         this.close();
      }

   }
}
