package util.log;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class LogContext {
   ReadWriteLock lock;
   Map<String, LogHandler> handlers;
   private final LinkedBlockingQueue<LogMsg> queue;

   public static LogContext instance() {
      return LogContextHolder.INSTANCE;
   }

   private LogContext() {
      this.lock = new ReentrantReadWriteLock(true);
      this.handlers = new HashMap();
      this.queue = new LinkedBlockingQueue();
      LogTask task = new LogTask(this.queue);
      task.start();
   }

   public void log(LogInfo log) {
      LogHandler handler = this.getHandler();
      handler.write(log);
   }

   private LogHandler getHandler() {
      Date now = new Date();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      String name = sdf.format(now);

      try {
         this.lock.readLock().lock();
         if (this.handlers.containsKey(name)) {
            LogHandler var4 = (LogHandler)this.handlers.get(name);
            return var4;
         }
      } finally {
         this.lock.readLock().unlock();
      }

      LogHandler handler;
      try {
         this.lock.writeLock().lock();
         if (!this.handlers.containsKey(name)) {
            handler = new LogHandler(name, this.queue);

            for(String other : this.handlers.keySet()) {
               if (!name.equals(other)) {
                  LogHandler timeOutHandler = (LogHandler)this.handlers.get(other);
                  timeOutHandler.close();
                  this.handlers.remove(other);
               }
            }

            this.handlers.put(name, handler);
            LogHandler var18 = handler;
            return var18;
         }

         handler = (LogHandler)this.handlers.get(name);
      } finally {
         this.lock.writeLock().unlock();
      }

      return handler;
   }

   static class LogContextHolder {
      static final LogContext INSTANCE = new LogContext();
   }
}
