/* KMLogger.cpp
 *
 * Copyright (C) 2023 OpenKylin, Inc
 */

#include "KMLogger.h"

#include <spdlog/sinks/rotating_file_sink.h>

#include <iostream>

// 最大日志文件大小和日志文件数量
#define LOG_FILE_MAX_SIZE 1024 * 1024 * 10
#define LOG_FILE_MAX_COUNT 10

KMLogger::KMLogger(token)
{
    m_logger = spdlog::rotating_logger_mt("file_logger", std::string(getenv("HOME")).append("/.log/kaiming-builder.log"), LOG_FILE_MAX_SIZE, LOG_FILE_MAX_COUNT);
    setLogLevel(spdlog::level::info);
}

KMLogger::~KMLogger() { }

void KMLogger::setLogLevel(spdlog::level::level_enum level)
{
    m_logLevel = level;
    m_logger->set_level(m_logLevel);
}

void KMLogger::setLogLevel(const std::string &level)
{
    setLogLevel(spdlog::level::from_str(level));
}

std::string KMLogger::format2String(const char *fmt, ...)
{
    char tmp[1024];
    memset(tmp, 0x00, 1024);
    va_list arg_list;
    va_start(arg_list, fmt);
    // sprintf(tmp, fmt, arg_list);
    vsprintf(tmp, fmt, arg_list);
    va_end(arg_list);
    std::cout << "llllog : " << tmp << std::endl;
    return std::string(tmp);
}

void KMLogger::traceLog(const std::string &msg)
{
    if (m_logLevel > spdlog::level::trace)
        return;

    std::cout << msg << std::endl;
    m_logger->trace(msg);
}

void KMLogger::debugLog(const std::string &msg)
{
    if (m_logLevel > spdlog::level::debug)
        return;

    std::cout << msg << std::endl;
    m_logger->debug(msg);
}

void KMLogger::infoLog(const std::string &msg)
{
    if (m_logLevel > spdlog::level::info)
        return;

    std::cout << msg << std::endl;
    m_logger->info(msg);
}

void KMLogger::warnLog(const std::string &msg)
{
    if (m_logLevel > spdlog::level::warn)
        return;

    std::cout << COLOR_YELLOW << "warn: " << COLOR_RESET << msg << std::endl;
    m_logger->warn(msg);
}

void KMLogger::errorLog(const std::string &msg)
{
    if (m_logLevel > spdlog::level::err)
        return;

    std::cerr << COLOR_RED << "error: " << COLOR_RESET << msg << std::endl;
    m_logger->error(msg);
}

void KMLogger::criticalLog(const std::string &msg)
{
    if (m_logLevel > spdlog::level::critical)
        return;

    std::cerr << COLOR_RED << "critical: " << COLOR_RESET << msg << std::endl;
    m_logger->critical(msg);
}
