#include "FileLogger.h"

#include <time.h>
#include <iomanip>
#include <iostream>
#include <filesystem>

FileLogger::~FileLogger()
{

}

void FileLogger::SetWorkDirectory(const std::string& workDir)
{
    mWorkDirectory = workDir;
}

void FileLogger::SetFileName(const std::string& fileName)
{
    mFileName = fileName;
}

void FileLogger::Open()
{
    if (mWorkDirectory.empty())
    {
        mWorkDirectory = std::filesystem::current_path().string();
    }
    mFileStream.open(mWorkDirectory + "/" + mFileName);
}

void FileLogger::Close()
{
    mFileStream.close();
}

void FileLogger::LogLine(const std::ostringstream& line)
{
    if (!mFileStream.is_open())
    {
        Open();
    }
    mFileStream << line.str() << std::endl;
}

void FileLogger::LogLine(const std::string& logType, const std::ostringstream& line, const std::string& fileName, const std::string& functionName, int lineNumber)
{
    std::time_t t = std::time(nullptr);
    const std::string cleanedFileName = fileName.substr(fileName.find_last_of("/\\") + 1);
    std::tm time_buf = { 0 };
#ifdef WIN32
    gmtime_s(&time_buf, &t);
#else
    gmtime_r(&t, &time_buf);
#endif
    std::cout << logType << "|" << std::put_time(&time_buf, "%T") << "|" << cleanedFileName << "::" << functionName << "::" << lineNumber << "|" << line.str() << std::endl;
    mFileStream << logType << "|" << std::put_time(&time_buf, "%T") << "|" << cleanedFileName << "::" << functionName << "::" << lineNumber << "|" << line.str() <<  std::endl;
}
