#include "ThingsBoardInterface.h"
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include "ChaletDevice.h"


CThingsBoardInterface::CThingsBoardInterface()
{
    mThingsBoardSocket = new QNetworkAccessManager;
    mThingsBoardRPCSocket = new QNetworkAccessManager;


    connect(mThingsBoardSocket,SIGNAL(finished(QNetworkReply*)),this,SLOT(ThingsBoardServerFinished(QNetworkReply*)));
    connect(mThingsBoardSocket,SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),this,SLOT(sslErrors(QNetworkReply*,QList<QSslError>)));

    connect(mThingsBoardRPCSocket,SIGNAL(finished(QNetworkReply*)),this,SLOT(ThingsBoardRPCFinished(QNetworkReply*)));
    connect(mThingsBoardRPCSocket,SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),this,SLOT(sslErrors(QNetworkReply*,QList<QSslError>)));
}

CThingsBoardInterface::~CThingsBoardInterface()
{
    mThingsBoardRPCReply->deleteLater();
    delete mThingsBoardRPCSocket;
    delete mThingsBoardSocket;

}

int CThingsBoardInterface::RegisterThingsboardRPC()
{

    QNetworkRequest Req;
    Req.setUrl(QUrl("http://192.168.50.225:8080/api/v1/qpJ6tWCkXHJzDQviDJ64/rpc"));

    mThingsBoardRPCReply = mThingsBoardRPCSocket->get(Req);
   // connect(mThingsBoardRPCReply,SIGNAL(readyRead()),this,SLOT(RPCData()));


    return 1;
}

void CThingsBoardInterface::UpdateChaletVoltage(float Voltage)
{
    // "{\"temperature\": 25}" http://localhost:8080/api/v1/$ACCESS_TOKEN/telemetry --header "Content-Type:application/json"
    //{"doubleKey":42.0}

    QByteArray JsonByteArray = "{\"Bat_Voltage\":";
    JsonByteArray.append((QString("%1}").arg(Voltage)).toUtf8().data());

    QNetworkRequest Req;
    Req.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    Req.setUrl(QUrl("http://192.168.50.225:8080/api/v1/qpJ6tWCkXHJzDQviDJ64/telemetry"));

    mThingsBoardSocket->post(Req,JsonByteArray);

}

void CThingsBoardInterface::UpdateChaletData(quint8 mInverterRelayStatus, quint8 mWiFiModuleStatus, qint8 mCurrentSensorStatus, float mBatteryVoltage, qint16 mBatteryCurrent, qint16 mBatterySOC, qint8 LoraState)
{
    //{"key1":"value1", "key2":"value2"}

    QByteArray JsonByteArray = "{\"Bat_Voltage\":";
    JsonByteArray.append((QString("%1, ").arg(mBatteryVoltage)).toUtf8().data());

    JsonByteArray.append("\"Bat_SOC\":");
    JsonByteArray.append((QString("%1, ").arg(mBatterySOC)).toUtf8().data());

    JsonByteArray.append("\"WiFi_State\":");
    JsonByteArray.append((QString("%1, ").arg(mWiFiModuleStatus)).toUtf8().data());

    JsonByteArray.append("\"CurrentSensor_State\":");
    JsonByteArray.append((QString("%1, ").arg(mCurrentSensorStatus)).toUtf8().data());

    JsonByteArray.append("\"Bat_Current\":");
    JsonByteArray.append((QString("%1, ").arg(mBatteryCurrent)).toUtf8().data());

    JsonByteArray.append("\"LoRa_State\":");
    JsonByteArray.append((QString("%1, ").arg(LoraState)).toUtf8().data());

    JsonByteArray.append("\"Inverter_State\":");
    JsonByteArray.append((QString("%1}").arg(mInverterRelayStatus)).toUtf8().data());

    QNetworkRequest Req;
    Req.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    Req.setUrl(QUrl("http://192.168.50.225:8080/api/v1/qpJ6tWCkXHJzDQviDJ64/telemetry"));

    mThingsBoardSocket->post(Req,JsonByteArray);

//    if(mThingsBoardRPCReply->isRunning() == true)
//    {
//        qDebug("RPC socket running...");
//    }
//    else
//    {
//        qDebug("RPC socket not runnging");
//    }
}

void CThingsBoardInterface::UpdateChaletData(CChaletMainStatus *Data)
{
    QByteArray JsonByteArray = "{\"Bat_Voltage\":";
    JsonByteArray.append((QString("%1, ").arg(Data->mBatteryVoltage)).toUtf8().data());

    JsonByteArray.append("\"Bat_SOC\":");
    JsonByteArray.append((QString("%1, ").arg(Data->mBatterySOC)).toUtf8().data());

    JsonByteArray.append("\"WiFi_State\":");
    JsonByteArray.append((QString("%1, ").arg(Data->mWiFiModuleStatus)).toUtf8().data());

    JsonByteArray.append("\"CurrentSensor_State\":");
    JsonByteArray.append((QString("%1, ").arg(Data->mCurrentSensorStatus)).toUtf8().data());

    JsonByteArray.append("\"Bat_Current\":");
    JsonByteArray.append((QString("%1, ").arg(Data->mBatteryCurrent)).toUtf8().data());

    JsonByteArray.append("\"LoRa_State\":");
    JsonByteArray.append((QString("%1, ").arg(Data->mIsOnline)).toUtf8().data());

    JsonByteArray.append("\"Inverter_State\":");
    JsonByteArray.append((QString("%1, ").arg(Data->mInverterRelayStatus)).toUtf8().data());

    JsonByteArray.append("\"Temperature_Sensor\":");
    JsonByteArray.append((QString("%1}").arg(Data->mChaletTemperature)).toUtf8().data());

    QNetworkRequest Req;
    Req.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    Req.setUrl(QUrl("http://192.168.50.225:8080/api/v1/qpJ6tWCkXHJzDQviDJ64/telemetry"));

    mThingsBoardSocket->post(Req,JsonByteArray);
}

void CThingsBoardInterface::ThingsBoardServerFinished(QNetworkReply *NetworkReply)
{
    if(NetworkReply->isFinished() == false)
        return;

    if(NetworkReply->error() != QNetworkReply::NoError)
    {
     //   qDebug("Network error... %d", NetworkReply->error());
        return;
    }


    QByteArray Reply = NetworkReply->readAll();
    if(Reply.isEmpty())
        return;

    NetworkReply->deleteLater();

    QString ReplyString(Reply);
    qDebug("ThingsBoard Server Reply: %s",ReplyString.toUtf8().data());
    ReplyString.remove("[\"");
    ReplyString.remove("\"]");
    QJsonValue Result(ReplyString);
//    QJsonParseError error;
//    QJsonDocument JsonReply = QJsonDocument::fromJson(Reply,&error);
//    QJsonObject JsonObject = JsonReply.object();
//    QStringList Keys = JsonObject.keys();

  //  int toto = ReplyString.toInt();
   // qDebug("Switch = %d",toto);
}

void CThingsBoardInterface::sslErrors(QNetworkReply *ServerReply, QList<QSslError> ErrorList)
{

    qDebug("Ssl errors...");
    ServerReply->ignoreSslErrors();
}


void CThingsBoardInterface::ThingsBoardRPCFinished(QNetworkReply *NetworkReply)
{
    if(mThingsBoardRPCReply->error() != QNetworkReply::NoError)
    {
     //   qDebug("Network error (ThingsBoardRPC)... %d", mThingsBoardRPCReply->error());
        RegisterThingsboardRPC();
        return;
    }


    QByteArray Reply = mThingsBoardRPCReply->readAll();
    if(Reply.isEmpty())
    {
        qDebug("Received an empty RPC reply  in ThiungsBoard...");
        RegisterThingsboardRPC();
        return;
    }

    mThingsBoardRPCReply->deleteLater();

    QString ReplyString(Reply);
    qDebug("ThingsBoard RPC Reply: %s",ReplyString.toUtf8().data());
    QJsonDocument JSonReply = QJsonDocument::fromJson(Reply);

    QJsonObject RPCCmd = JSonReply.object();

    QJsonValue RequestedCmd = RPCCmd.value("method");
    {
        if(RequestedCmd.toString().contains("setChaletInverterState"))
        {
            //Fetch the required state.
            bool RequestedState = RPCCmd.value("params").toBool();
            if(RequestedState == true)
            {
               qDebug("Server Inverter TURN ON request received.");
             //  mChaletLoraDevice->SendInverterPowerRelayState(true);
            }
            if(RequestedState == false)
            {
               qDebug("Server Inverter TURN OFF request received.");
             //  mChaletLoraDevice->SendInverterPowerRelayState(false);
            }


        }
        else if(RequestedCmd.toString().contains("setChaletWiFiState"))
        {
            //Fetch the required state.
            QString RequestedState = RPCCmd.value("params").toString();
            if(RequestedState == "true")
            {
               qDebug("Server WiFi TURN ON request received.");
            }
            if(RequestedState == "false")
            {
               qDebug("Server WiFi TURN OFF request received.");
            }
        }
        else if(RequestedCmd.toString().contains("getChaletInverterState"))
        {
            qDebug("Inverter state request received");
            QByteArray JsonByteArray;
            int ReqID = RPCCmd.value("id").toInt();
            if(mChaletLoraDevice->IsInverterON())
            {
                JsonByteArray = "{\"InverterSwitchState\":\"1\"}";
            }
            else
            {
                JsonByteArray = "{\"InverterSwitchState\":\"0\"}";
            }

            QNetworkRequest Req;
//            QString URL = QString("http://192.168.50.225:8080/api/v1/qpJ6tWCkXHJzDQviDJ64/rpc/%1").arg(ReqID);
            QString URL = QString("http://192.168.50.225:8080/api/v1/qpJ6tWCkXHJzDQviDJ64/attributes");
            Req.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
            Req.setUrl(QUrl(URL));

            mThingsBoardSocket->post(Req,JsonByteArray);
        }
        else
        {
            qDebug("Received an unknown RPC call from ThingsBoard server");
        }
    }

    //Re-register for next request..
    RegisterThingsboardRPC();
}

void CThingsBoardInterface::RPCsslErrors(QNetworkReply *ServerReply, QList<QSslError> ErrorList)
{

    qDebug("Ssl errors...");
    ServerReply->ignoreSslErrors();
}

void CThingsBoardInterface::RPCData()
{
//    if(mThingsBoardRPCReply->isFinished() == false)
//        return;

//    if(mThingsBoardRPCReply->error() != QNetworkReply::NoError)
//    {
//        qDebug("Network error (RPCData)... %d", mThingsBoardRPCReply->error());
//        RegisterThingsboardRPC();
//        return;
//    }


//    QByteArray Reply = mThingsBoardRPCReply->readAll();
//    if(Reply.isEmpty())
//    {
//        qDebug("Received an empty RPC reply  in ThiungsBoard...");
//        RegisterThingsboardRPC();
//        return;
//    }

//    mThingsBoardRPCReply->deleteLater();

//    QString ReplyString(Reply);
//    qDebug("ThingsBoard RPC Reply: %s",ReplyString.toUtf8().data());
//    QJsonDocument JSonReply = QJsonDocument::fromJson(Reply);

//    QJsonObject RPCCmd = JSonReply.object();

//    QJsonValue RequestedCmd = RPCCmd.value("method");
//    {
//        if(RequestedCmd.toString().contains("setChaletInverterState"))
//        {
//            //Fetch the required state.
//            bool RequestedState = RPCCmd.value("params").toBool();
//            if(RequestedState == true)
//            {
//               qDebug("Server Inverter TURN ON request received.");
//               //mChaletLoraDevice->SendInverterPowerRelayState(true);
//            }
//            if(RequestedState == false)
//            {
//               qDebug("Server Inverter TURN OFF request received.");
//              // mChaletLoraDevice->SendInverterPowerRelayState(false);
//            }


//        }
//        else if(RequestedCmd.toString().contains("setWiFiState"))
//        {
//            //Fetch the required state.
//            QString RequestedState = RPCCmd.value("params").toString();
//            if(RequestedState == "true")
//            {
//               qDebug("Server WiFi TURN ON request received.");
//            }
//            if(RequestedState == "false")
//            {
//               qDebug("Server WiFi TURN OFF request received.");
//            }
//        }
//        else
//        {
//            qDebug("Received an unknown RPC call from ThingsBoard server");
//        }
//    }

//    //Re-register for next request..
//    RegisterThingsboardRPC();


}
