#include "lrcparser.h"
#include <QFile>
#include <QStringList>
#include <QRegularExpression>
#include <QTextStream>
#include <QDebug>

QList<LrcLine> LrcParser::parseLrc(const QString &filePath) {
    QList<LrcLine> lines;
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件:" << filePath;
        return lines;
    }

    QTextStream in(&file);
    while (!in.atEnd()) {
        QString line = in.readLine();
        QRegularExpression re("\\[(\\d{2}:\\d{2}.\\d{2})\\] (.*)");
        QRegularExpressionMatch match = re.match(line);
        if (match.hasMatch()) {
            QString timeStr = match.captured(1);
            int timeMs = timeStrToMs(timeStr);
            QString text = match.captured(2);
            lines.append({timeMs, text});
        }
    }
    file.close();
    return lines;
}

int LrcParser::timeStrToMs(const QString &timeStr) {
    QRegularExpression re("(\\d{2}):(\\d{2}).(\\d{2})");
    QRegularExpressionMatch match = re.match(timeStr);
    if (match.hasMatch()) {
        int minutes = match.captured(1).toInt();
        int seconds = match.captured(2).toInt();
        int milliseconds = match.captured(3).toInt() * 100;
        return (minutes * 60 + seconds) * 1000 + milliseconds;
    }
    return -1;
}
