#include "FreqReplicator.h"

#include <iostream>
#include <QDateTime>

FreqReplicator::FreqReplicator(QObject *parent) : DeviceBase(parent)
{
    connect(&this->serialUtil, &QSerialPortUtil::dataRecieved,
            this, &FreqReplicator::dataReceivedHandler);

    kafkaUtil.setBrokers(SettingConfig::getInstance().KAFKA_BROKERS);
    kafkaUtil.setTopic(SettingConfig::getInstance().KAFKA_DATA_TOPIC);
    kafkaUtil.createProducer();

    this->protocol = DeviceStatusProtocolBase::deviceStatusProtocolFactory(typeid (this).name());
}

FreqReplicator::~FreqReplicator()
{
    disconnect(&this->serialUtil, &QSerialPortUtil::dataRecieved,
               this, &FreqReplicator::dataReceivedHandler);
}

void FreqReplicator::dataReceivedHandler(QByteArray data)
{
    this->dataBuff.append(data);

    std::cout << QByteUtil::binToHexString(dataBuff).toStdString() << std::endl;

    QList<QByteArray> frameList = protocol->extractFrameList(this->dataBuff);

    if (frameList.size() > 0)
    {
        for (int i = 0; i < frameList.size(); i++)
        {
            QByteArray frameByte = frameList.at(i);

            int frameType = protocol->checkFrame(frameByte);
            DeviceFrameBaseDto * frameDto = protocol->frameFactory(frameType);
            if (frameDto != nullptr)
            {
                // ★解析成数据对象
                bool parse = protocol->parseDeviceFrameData(frameByte, frameDto, frameType);

                // 解析成功
                if (parse == true)
                {
                    QDateTime now = QDateTime::currentDateTime();
                    frameDto->timestamp = now.toString("yyyy-MM-dd HH:mm:ss.zzz");
                    frameDto->milisecond = now.toMSecsSinceEpoch();
                    frameDto->rawFrame = frameByte;

                    this->afterFramePhase(frameDto);
                }

                // 在此处释放内存，不影响后续显示
                // 不在此处释放内存则会导致内存持续增加
                // 具体原因不明
                delete frameDto;
            }
        }
    }
}

void FreqReplicator::afterFramePhase(DeviceFrameBaseDto * frameDto)
{
    std::cout << "frame type: " << typeid(* frameDto).name() << std::endl;
    std::cout << QByteUtil::binToHexString(frameDto->rawFrame).toStdString() << std::endl;

    // 3. 输出到中间件，执行后续处理过程
    if (SettingConfig::getInstance().NEED_KAFKA == 1)
    {
        QJsonObject jsonObj = frameDto->toJSON();
        jsonObj.insert("clientId", SettingConfig::getInstance().CLIENT_ID);
        jsonObj.insert("deviceId", deviceId);
        kafkaUtil.produceMessage(QString(QJsonDocument(jsonObj).toJson(QJsonDocument::Compact)));
    }
}
