#include "CounterProtocolBM.h"
#include <iostream>

CounterProtocolBM::CounterProtocolBM(QObject *parent) : QObject(parent)
{

}

CounterProtocolBM::~CounterProtocolBM()
{

}

bool CounterProtocolBM::parseMessureData(QByteArray rawData, CounterDataDto * counterData)
{
    int start = rawData.indexOf(COUNTER_FRAME_CONTENT_SEP);
    int end = rawData.indexOf(COUNTER_FRAME_SUM_SEP);

    QByteArray content = rawData.mid(start + 1, end - start - 1);
    QString contentStr = QString(content);
    QStringList subList = contentStr.split(",");

    counterData->type = subList.at(0).toUInt();
    counterData->channelId = subList.at(1).toUInt();
    counterData->channelActive = subList.at(2).toUInt();
    counterData->channelRefId = subList.at(3).toUInt();
    counterData->channelData = subList.at(4).toLongLong(); //
    counterData->load = subList.at(5);
    counterData->level = subList.at(6).toDouble();
    counterData->frameId = subList.at(7);

    return true;
}

QList<QByteArray> CounterProtocolBM::extractFrameList(QByteArray rawData)
{
    QList<QByteArray> resultList;
    int head = rawData.indexOf(COUNTER_FRAME_HEAD);
    if (head < 0)
    {
        return resultList;
    }
    int tail = rawData.lastIndexOf(COUNTER_FRAME_TAIL);
    if (tail < 0)
    {
        return resultList;
    }
    rawData = rawData.mid(head, tail - head + 2);
    std::cout << rawData.toStdString() << std::endl;

    if (rawData.endsWith(QByteArray("\r\n")) == true && rawData.startsWith("$GL") == true)
    {
        QByteArray ba;
        for (int i = 0; i < rawData.size() - 1; i++)
        {
            if (rawData.at(i) != '\r')
            {
                ba.append(rawData.at(i));
            } else
            {
                if (rawData.at(i + 1) == '\n')
                {
                    ba.append("\r\n");
                    resultList.append(ba);
                    ba.clear();
                    i++;
                } else
                {
                    ba.append(rawData.at(i));
                }
            }
        }
    }

    return resultList;
}

bool CounterProtocolBM::checkFrame(QByteArray rawData)
{
    // 帧长度小于最小的长度
    if (rawData.size() < COUNTER_FRAME_MIN_LENGTH)
    {
        return false;
    }

    // 帧头不是$GL
    if ("$GL,0" != rawData.mid(0, 5))
    {
        return false;
    }

    // 帧尾不是\r\n
    if (COUNTER_FRAME_TAIL.toLocal8Bit() != rawData.mid(rawData.size() - COUNTER_FRAME_TAIL.size()))
    {
        return false;
    }

    // 校验和的分隔符不是*
    if (COUNTER_FRAME_SUM_SEP.toLocal8Bit() != rawData.mid(rawData.size() - COUNTER_FRAME_TAIL.size() - 2 - 1, 1))
    {
        return false;
    }

    return true;
}
