#include <chrono>
#include <thread>
#include "log.h"

std::fstream Logger::_file;
std::mutex Logger::_locker;

void Logger::Open()
{
    _file.open("log.txt", std::ios::out);

    if(_file.fail()) {
        throw std::runtime_error("Can't create log file");
    }
}

void Logger::Close()
{
    _locker.lock();

    _file.close();

    _locker.unlock();
}

void Logger::Debug(const std::string &message, ...)
{
    va_list args;
    va_start(args, message);
    Logger::_out(message, "debug", args);
    va_end(args);
}

void Logger::Warning(const std::string &message, ...)
{
    va_list args;
    va_start(args, message);
    Logger::_out(message, "warning", args);
    va_end(args);
}

void Logger::Error(const std::string &message, ...)
{
    va_list args;
    va_start(args, message);
    Logger::_out(message, "error", args);
    va_end(args);
}

void Logger::_out(const std::string &message, const std::string &type, va_list args)
{
    static char buffer[16*1024] = {0};

    _locker.lock();

    uint32_t time = std::clock();
    int length;

    length = snprintf(buffer, 16*1024, "%d: [%d] (%s) => ", time, std::this_thread::get_id(), type.c_str());

    _file.write(buffer, length);

    length = vsnprintf(buffer, 16*1024, message.c_str(), args);

    _file.write(buffer, length);
    _file.write("\r\n", 2);

    _file.flush();

    _locker.unlock();
}
