#include "devicetypeinfluxdbwriter.h"

DeviceTypeInfluxdbWriter::DeviceTypeInfluxdbWriter(QObject *parent) : QObject(parent)
{
    isSend = true;

    logthread = new logThread(this);
    logthread->start();

    mqttthread = new MqttThread(this);
    connect(mqttthread,&MqttThread::mqttLog,this,&DeviceTypeInfluxdbWriter::dataListLog);
    connect(mqttthread,&MqttThread::sendDevData,this,&DeviceTypeInfluxdbWriter::receiveDevData);

    timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,&DeviceTypeInfluxdbWriter::time_out);

    networkmanager = new QNetworkAccessManager(this);
    connect(networkmanager,&QNetworkAccessManager::finished,this,&DeviceTypeInfluxdbWriter::finishedSlot);
}

DeviceTypeInfluxdbWriter::~DeviceTypeInfluxdbWriter()
{
    logthread->stop();

}

void DeviceTypeInfluxdbWriter::start()
{
    timer->start(200);
    mqttthread->start();
}

void DeviceTypeInfluxdbWriter::time_out()
{
    if((datalist.length()>0)&&(isSend)){
        isSend = false;
        QString data = datalist.first();

        QByteArray Report = data.toUtf8();
        QNetworkRequest *req = new QNetworkRequest();
        req->setUrl(QUrl("http://172.16.120.69:8086/write?db=USKTSDB_B&u=root&p=root"));
        req->setHeader(QNetworkRequest::ContentTypeHeader,"application/json; charset=UTF-8");
        req->setHeader(QNetworkRequest::ContentLengthHeader,QString("%1").arg(Report.length()).toUtf8());
        QNetworkReply *reply = networkmanager->post(*req,Report);
        QReplyTimeout *pTimeout = new QReplyTimeout(reply,10000);
        connect(pTimeout, SIGNAL(net_timeout()),this,SLOT(reply_timeout()));
    }
}

void DeviceTypeInfluxdbWriter::reply_timeout()
{
    if(datalist.length()>0){
        datalist.removeFirst();
    }
    isSend = true;
}

void DeviceTypeInfluxdbWriter::finishedSlot(QNetworkReply *reply)
{
    if(datalist.length()>0){
        if(reply->error()==QNetworkReply::NoError){
            QString bak_info = QString::fromUtf8(reply->readAll());

        }else{

        }

        datalist.removeFirst();
    }
    reply->deleteLater();
    isSend = true;
}

void DeviceTypeInfluxdbWriter::dataListLog(QString log)
{
    logthread->appendData(log);
}


void DeviceTypeInfluxdbWriter::receiveDevData(QString data)
{
    datalist.append(data);
}
