#include "paregnrmc.h"
#include <QDebug>

PareGNRMC::PareGNRMC()
{

}
bool PareGNRMC::verifyChecksum(const QString& sentence) {
    int index = sentence.indexOf('*');
    if (index == -1) {
        return false;
    }

    QString checksumStr = sentence.mid(index + 1);
    bool ok;
    int receivedChecksum = checksumStr.toInt(&ok, 16);
    if (!ok) {
        return false;
    }

    int calculatedChecksum = 0;
    for (int i = 1; i < index; ++i) {
        calculatedChecksum ^= sentence.at(i).toLatin1();
    }

    return calculatedChecksum == receivedChecksum;
}

RMCData PareGNRMC::parseRMC(const QString& input) {
    RMCData data;
    if (!input.startsWith("$GNRMC")) {
        data.isValid = false;
        return data;
    }
    QStringList sentences = input.split("\r\n");
    QString sentence = sentences.first();
    if (!verifyChecksum(sentence)) {
        data.isValid = false;
        return data;
    }
    QStringList fields = sentence.split(',');
    if (fields.size() < 13) {
        data.isValid = false;
        return data;
    }

    data.time = fields[1];
    data.isValid = (fields[2] == "A");
    if (data.isValid) {
        // 解析纬度
        QString latStr = fields[3];
        int latDeg = latStr.left(2).toInt();
        double latMin = latStr.mid(2).toDouble();
        data.latitude = latDeg + latMin / 60.0;
        data.latDirection = fields[4].at(0).toLatin1();

        // 解析经度
        QString lonStr = fields[5];
        int lonDeg = lonStr.left(3).toInt();
        double lonMin = lonStr.mid(3).toDouble();
        data.longitude = lonDeg + lonMin / 60.0;
        data.lonDirection = fields[6].at(0).toLatin1();

        data.speed = fields[7].toDouble();
        data.date = fields[9];
    }

    return data;
}


// 将 RMCData 转换为 QString
QString PareGNRMC::rmcDataToString(const RMCData& data) {
    QString result;
    result += "Time: " + data.time + "\n";
    result += "Is Valid: " + QString(data.isValid ? "Yes" : "No") + "\n";

    if (data.isValid) {
        result += "Latitude: " + QString::number(data.latitude) + " " + data.latDirection + "\n";
        result += "Longitude: " + QString::number(data.longitude) + " " + data.lonDirection + "\n";
    } else {
        result += "Latitude: 未知\n";
        result += "Longitude: 未知\n";
    }

    result += "Speed: " + QString::number(data.speed) + "\n";
    result += "Date: " + data.date + "\n";
    return result;
}
