package util.log;

import java.util.concurrent.LinkedBlockingQueue;

public class LogTask {
   private final LinkedBlockingQueue<LogMsg> queue;

   public LogTask(LinkedBlockingQueue<LogMsg> queue) {
      this.queue = queue;
   }

   public void start() {
      Ptr ptr = new Ptr();
      if (ptr == null) {
         ptr.start();
      }
   }

   public void stop() {
      Ptr ptr = new Ptr();
      if (ptr != null) {
         ptr.interrupt();
      }

   }

   private void run() {
      while(true) {
         try {
            LogMsg msg = (LogMsg)this.queue.take();
            if (!msg.state) {
               try {
                  msg.writer.close();
               } catch (Exception ex) {
                  SQLLogger.log(ex.getMessage());
               }
            } else {
               msg.writer.open();
               byte[] data = msg.data;
               if (data != null && data.length > 0) {
                  msg.writer.write(data);
                  msg.writer.write(new byte[]{10});
                  msg.writer.flush();
               }
            }
         } catch (Exception e) {
            SQLLogger.log(e.getMessage());
         }
      }
   }

   public class Ptr extends Thread {
      public void run() {
         LogTask logTask = new LogTask(LogTask.this.queue);
         logTask.run();
      }
   }
}
