#include "logger.h"

#include <cstdint>
#include <iostream>
#include <syncstream>

using namespace std;
//--------------------------------------------------------------
/* Constructor */
Logger::Logger(sdi_toolBox::desktop::eventBus::Bus &hBus)
  : Node(hBus)
{
  // Subscribe to log message types to receive messages
  subscribe(HashMessageType("Log"));

  // Start the logger's main thread to process incoming messages
  run();
}
//--------------------------------------------------------------
/* Default destructor */
Logger::~Logger()
{
  // Stop the logger's main thread and clean up resources
  stop();
}
//--------------------------------------------------------------
/* Start the logger's main thread to process incoming messages */
void Logger::run()
{
  stop();
  m_thread = std::jthread([this](const std::stop_token &token)
                          { processLogMessages(token); });
}
//--------------------------------------------------------------
/* Stop the logger's main thread and clean up resources */
void Logger::stop()
{
  m_thread.request_stop();
  messageNotify();
  if (m_thread.joinable())
    m_thread.join();
}
//--------------------------------------------------------------
/* Process incoming log messages from the event bus */
void Logger::processLogMessages(const std::stop_token &token)
{
  while (!token.stop_requested())
  {
    syncWaitForMessage();

    while (getMessageCount() > 0)
    {
      const auto message = dynamic_pointer_cast<BasicMessage>(popMessage());
      if (!message)
        continue;

      osyncstream synced_out(std::cout);
      synced_out << message->debug() << endl;
    }
  }
}
//--------------------------------------------------------------
