#include "ConsoleSession.h"
#include "Log.h"
#include "ConsoleServer.h"

namespace core {

   ConsoleServer *Log::consoleServer = NULL;
   File *Log::logFile = NULL;
   int Log::seq = 0;
   
   Log::Log(ConsoleServer *consoleServer) {
      this->consoleServer = consoleServer;
   }
   
   Log::Log(File *logFile) {
      this->logFile = logFile;
   }
   
   Log::Log(int level) {
      
      output = true;
      
      auto clock = std::chrono::system_clock::now();
      time_t theTime = std::chrono::system_clock::to_time_t(clock);
      std::string timeOut = std::string(ctime(&theTime));
      timeOut = timeOut.substr(0, timeOut.length() - 1);
      
      *this << timeOut;
      *this << " ";
      
      switch(level) {
       case LOG_NONE:
         *this << "[NONE]  :";
         break;
       case LOG_INFO:
         *this << "[INFO]  :";
         break;
       case LOG_WARN:
         *this << "[WARN]  :";
         break;
       case LOG_EXCEPT:
         *this << "[EXCEPT]: ";
         break;
       case LOG_DEBUG_1:
         *this << "[DEBUG1]: ";
         break;
       case LOG_DEBUG_2:
         *this << "[DEBUG2]:  ";
         break;
       case LOG_DEBUG_3:
         *this << "[DEBUG3]:   ";
         break;
       case LOG_DEBUG_4:
         *this << "[DEBUG4]:    ";
         break;
       default:
         *this << "[?]     ?";
         break;      
      };
   }
   
   Log::~Log() {
      
      if(output) {
	 
	 std::stringstream out;
	 out << seq << "." << this->str() << std::endl;;
	 
	 if(consoleServer) 
	   consoleServer->sendToConnectedConsoles(out.str());
	 
	 if(logFile)
	   logFile->write(out.str());
	 
	 std::cout << out.str();
	 ++seq;
      }
   }
   
}
