#include "TimeReplicatorProtocolBM.h"

TimeReplicatorProtocolBM::TimeReplicatorProtocolBM(QObject *parent) : DeviceStatusProtocolBase(parent)
{

}

TimeReplicatorProtocolBM::~TimeReplicatorProtocolBM()
{

}

bool TimeReplicatorProtocolBM::parseDeviceFrameData(QByteArray rawData, DeviceFrameBaseDto *frameData, int frameType)
{
    if (frameType != 1)
        return false;

    qint8 length = rawData.mid(1, 2).toInt(0, 16);
    QByteArray content = rawData.mid(19, length - 24);
    qint8 count;
    int inputByte = 0;
    QString outStr = "";

    ((TimeReplicatorStatusDto *) frameData)->devStatus = content.at(0);
    if (length < 0x30)
    {
        count = 2;
        inputByte = content.mid(2, 1).toInt();
        outStr = content.mid(3, 8 * count);
    } else
    {
        count = 4;
        inputByte = content.mid(2, 2).toInt();
        outStr = content.mid(4, 8 * count);
    }

    ((TimeReplicatorStatusDto *) frameData)->inCount = count;
    for (int i = 0; i < count; i++)
    {
        qint8 in = inputByte % 2;
        ((TimeReplicatorStatusDto *) frameData)->inValid.append(in == 1 ? "1" : "0");
        inputByte = inputByte / 2;

        QString output = "";
        for (int j = 0; j < 8; j++)
        {
            output += outStr.at(i * 8 + j);
            output += ",";
        }
        ((TimeReplicatorStatusDto *) frameData)->outValid.append(output.mid(0, output.size() - 1));
    }

    ((TimeReplicatorStatusDto *)frameData)->frameType = TIME_REPLICATOR_STATUS_FRAME_TYPE;

    return true;
}

int TimeReplicatorProtocolBM::checkFrame(QByteArray rawData)
{
    if (rawData.at(0) == '$' && rawData.at(rawData.size() - 1) == '*' &&
            rawData.at(3) == '2' && rawData.at(20) == '2' &&
            rawData.size() == rawData.mid(1, 2).toInt(0, 16))
        return 1;
    return 0;
}

DeviceFrameBaseDto * TimeReplicatorProtocolBM::frameFactory(int frameType)
{
    DeviceFrameBaseDto * frameData = new TimeReplicatorStatusDto();

    return frameData;
}

QList<QByteArray> TimeReplicatorProtocolBM::extractFrameList(QByteArray rawData)
{
    QList<QByteArray> resultList;
    while (rawData.endsWith(QByteArray("*")) == true && rawData.startsWith("$") == true)
    {
        QByteArray ba;
        qint8 length = rawData.mid(1, 2).toInt(0, 16);
        if (rawData.at(0) == '$' && rawData.at(length - 1) == '*')
        {
            ba.append(rawData.mid(0, length));
            resultList.append(ba);
            ba.clear();
            rawData = rawData.mid(length, rawData.size() - length);
        } else
        {
            break;
        }
    }

    return resultList;
}
