#include "LogHandler.h"
#include <QDateTime>
#include <QMetaObject>
#include <iostream>

// 初始化静态成员
LogHandler* LogHandler::s_instance = nullptr;
QMutex      LogHandler::s_mutex;

LogHandler::LogHandler(QObject *parent) : QObject(parent), m_logWidget(nullptr) {

}

// 获取单例实例（线程安全）
LogHandler* LogHandler::log_instance() {
    if (!s_instance) {
        QMutexLocker locker(&s_mutex);
        if (!s_instance) {
            s_instance = new LogHandler();
        }
    }
    return s_instance;
}

// 初始化日志输出目标
void LogHandler::log_init(QPlainTextEdit *logWidget) {
    LogHandler *handler = log_instance();
    handler->m_logWidget = logWidget;
    qInstallMessageHandler(log_handleMessage);  // 注册消息处理器
}

// 静态消息处理函数
void LogHandler::log_handleMessage(QtMsgType type, const QMessageLogContext &, const QString &msg) {
    LogHandler *handler = log_instance();
    if (!handler) return;

    // 格式化日志消息（添加时间和日志级别）
    QString timestamp = QDateTime::currentDateTime().toString("[hh:mm:ss.zzz] ");
    QString level;
    switch (type) {
        case QtDebugMsg:    level = "DEBUG"; break;
        case QtInfoMsg:     level = "INFO"; break;
        case QtWarningMsg:  level = "WARN"; break;
        case QtCriticalMsg: level = "ERROR"; break;
        case QtFatalMsg:    level = "FATAL"; break;
    }
    QString formattedMsg = QString("%1[%2] %3").arg(timestamp, level, msg);

    // 如果有UI组件，通过信号槽更新（线程安全）
    if (handler->m_logWidget) {
        emit handler->log_messageLogged(formattedMsg);
    } else {
        // 无UI时输出到控制台
        std::cerr << formattedMsg.toStdString() << std::endl;
    }
}
