#include "DeviceStatusProtocolBase.h"
#include "SignalGeneratorProtocolBM.h"
#include "FrequencyTuningProtocolBM.h"
#include "TimeSwitcherProtocolBM.h"
#include "FreqSwitcherProtocolBM.h"
#include "TimeReplicatorProtocolBM.h"
#include "FreqReplicatorProtocolTX.h"
#include "BCodeTerminalProtocolBM.h"

#include <iostream>

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

}

DeviceStatusProtocolBase * DeviceStatusProtocolBase::deviceStatusProtocolFactory(QString deviceType)
{
    std::cout << deviceType.toStdString() << std::endl;
    if (deviceType.contains("SignalGenerator") == true)
    {
        return new SignalGeneratorProtocolBM();
    } else if (deviceType.contains("FrequencyTuning") == true)
    {
        return new FrequencyTuningProtocolBM();
    } else if (deviceType.contains("TimeSwitcher") == true)
    {
        return new TimeSwitcherProtocolBM();
    } else if (deviceType.contains("FreqSwitcher") == true)
    {
        return new FreqSwitcherProtocolBM();
    } else if (deviceType.contains("FreqReplicator") == true)
    {
        return new FreqReplicatorProtocolTX();
    } else if (deviceType.contains("TimeReplicator") == true)
    {
        return new TimeReplicatorProtocolBM();
    } else if (deviceType.contains("BCodeTerminal") == true)
    {
        return new BCodeTerminalProtocolBM();
    }

    return nullptr;
}

QByteArray DeviceStatusProtocolBase::generateSettingCommand(QString commandType, QString valueSet)
{
    QByteArray commandBytes;
    commandBytes.append(commandType).append(",");
    commandBytes.append(valueSet);

    QString xorValue = this->calculateXOR(commandBytes);

    commandBytes.prepend("$");
    commandBytes.append("*");
    commandBytes.append(xorValue);

    return commandBytes;
}

QString DeviceStatusProtocolBase::calculateXOR(QByteArray byteArray)
{
    quint8 xorValue = 0;

    for (int i =0; i < byteArray.size(); i++)
    {
        xorValue = xorValue ^ byteArray.at(i);
    }

    QString str;
    str.sprintf("%02X", xorValue);
    return str;
}
