#include "FormLogShow.h"
#include "ui_FormLogShow.h"

#include <QDir>
#include <QFile>
#include <QTextStream>
#include <QScroller>

#include "GeneralInterface.h"
#include "LanguageManager.h"

FormLogShow::FormLogShow(BaseWidget *parent)
    : BaseWidget(parent)
    , ui(new Ui::FormLogShow)
{
    ui->setupUi(this);

    ui->log->setReadOnly(true);
    ui->log->setTextInteractionFlags(Qt::NoTextInteraction);

    QScroller::grabGesture(ui->log,              QScroller::TouchGesture);
    QScroller::grabGesture(ui->log->viewport(),  QScroller::LeftMouseButtonGesture);

    connect(LanguageManager::instance(), &LanguageManager::languageChanged, this, [this]() { ui->retranslateUi(this); });
}

FormLogShow::~FormLogShow()
{
    delete ui;
}

bool FormLogShow::returnParent()
{
    return true;
}

void FormLogShow::setLogType(int newLogType)
{
    m_logType = newLogType;
    setWindowTitle(GeneralInterface::getWindowTitle(m_logType));
}

void FormLogShow::refreshLogLog()
{
    ui->log->clear();
    auto filePath = GeneralInterface::getLogFilePath(m_logType);

    QDir logDir(filePath);
    // 只查找 .log 文件，可根据实际情况修改
    QStringList filters;
    filters << "*.log";
    QFileInfoList fileList = logDir.entryInfoList(filters, QDir::Files | QDir::NoSymLinks, QDir::Name);

    ui->log->clear();
    for (const QFileInfo& fileInfo : std::as_const(fileList)) {
        QFile file(fileInfo.absoluteFilePath());
        if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream in(&file);
            // ui->log->append(QString("==== %1 ====").arg(fileInfo.fileName()));
            ui->log->append(in.readAll());
            ui->log->append("\n");
            file.close();
        }
    }
}

void FormLogShow::showEvent(QShowEvent *event)
{
    refreshLogLog();
    QWidget::showEvent(event);
}
