#include "logger.h"
#include <chrono>
#include <fstream>
#include <iostream>
#include <windows.h>

namespace
{

    void set_color(int textColor, int bgColor)
    {
        HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
        SetConsoleTextAttribute(hConsole,
            static_cast<WORD>(bgColor << 4) | textColor);
    }

    void reset_color() { set_color(7, 0); }

    // The console window lives inside the game process, so it dies together with the
    // process on a crash and the last lines are lost. Mirror every log line to a file,
    // opening/flushing/closing per call so each line is on disk before we return and
    // survives any subsequent crash.
    void file_log(const char* level, const std::string& msg)
    {
        std::ofstream f("C:\\tarkovaddons_log.txt", std::ios::app);
        if (f.is_open())
        {
            f << "[" << level << "] " << msg << std::endl;
            f.flush();
        }
    }
}

namespace logger
{
    void info(std::string msg)
    {
        std::cout << "[";
        set_color(3, 0);
        std::cout << "INFO";
        reset_color();
        std::cout << "] ";
        std::cout << msg << std::endl; // endl flushes: keep logs visible if the game crashes after
        file_log("INFO", msg);
    }

    void warn(std::string msg)
    {
        std::cout << "[";
        set_color(6, 0);
        std::cout << "WARN";
        reset_color();
        std::cout << "] ";
        std::cout << msg << std::endl; // endl flushes: keep logs visible if the game crashes after
        file_log("WARN", msg);
    }

    void error(std::string msg)
    {
        std::cout << "[";
        set_color(4, 0);
        std::cout << "ERROR";
        reset_color();
        std::cout << "] ";
        std::cout << msg << std::endl; // endl flushes: keep logs visible if the game crashes after
        file_log("ERROR", msg);
    }
}
