#include <loggingconsumer.h>
#include <eventsystem.h>
#include <filepath.h>

using namespace Sia::Api;

CLoggingConsumer::CLoggingConsumer(const EventLevel& eventLevel) :
  _EventLevel(eventLevel)
{
	CEventSystem::EventSystem.AddEventConsumer([=](const CEvent& event) {this->ProcessEvent(event); });
}


CLoggingConsumer::~CLoggingConsumer()
{
}

void CLoggingConsumer::ProcessEvent(const CEvent& eventData)
{
  if (eventData.GetEventLevel() <= GetEventLevel())
  {
    // TODO Implement rolling/max size and timestamp
    FilePath logPath("~\\siadrive\\logs\\siadrive.log");
    logPath.Resolve();
    FilePath(logPath).RemoveFileName().CreateDirectory();

    std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
    std::stringstream ss;
    ss << std::put_time(std::localtime(&now), "%F %T ");

    FILE* logFile;
    if (fopen_s(&logFile, SString::ToUtf8(static_cast<SString>(logPath)).c_str(), "a+") == 0)
    {
      std::string msg = SString::ToUtf8(ss.str() + eventData.GetSingleLineMessage() + "\n");
      fwrite(&msg[0], 1, msg.length(), logFile);
      fclose(logFile);
    }
  }
}