package util.log;

import java.util.concurrent.LinkedBlockingQueue;

public class LogHandler {
   private LinkedBlockingQueue<LogMsg> queue;
   private final LogWriter writer;
   private final String name;

   public LogHandler(String name, LinkedBlockingQueue<LogMsg> queue) {
      this.name = name;
      this.queue = queue;
      String logfile = "sql_" + name + ".log";
      this.writer = new LogWriter(logfile);
   }

   public boolean write(LogInfo data) {
      if (this.writer.open()) {
         byte[] bytes = data.buffer();
         if (bytes == null) {
            return false;
         } else {
            LogMsg msg = new LogMsg();
            msg.data = bytes;
            msg.writer = this.writer;
            msg.name = this.name;
            msg.state = true;
            this.queue.add(msg);
            return true;
         }
      } else {
         return false;
      }
   }

   public void close() {
      LogMsg msg = new LogMsg();
      msg.data = null;
      msg.writer = this.writer;
      msg.name = this.name;
      msg.state = false;
      this.queue.add(msg);
   }
}
