#include "ChaletHomeServerInterface.h"

CChaletHomeServerInterface::CChaletHomeServerInterface()
{
    mConnectionTimer = new QTimer;
    connect(&mMQTTClient,&QMqttClient::stateChanged,this,&CChaletHomeServerInterface::StateChanged);
    connect(&mMQTTClient,&QMqttClient::errorChanged,this,&CChaletHomeServerInterface::MQTTClientError);
    connect(mConnectionTimer,&QTimer::timeout,this,&CChaletHomeServerInterface::ConnectionTimerExpired);

    mConnectionTimer->setSingleShot(true);
}

CChaletHomeServerInterface::~CChaletHomeServerInterface()
{
    DisconnectFromServer();
    delete mConnectionTimer;
}

int CChaletHomeServerInterface::Start()
{
     mConnectionTimer->start(1000);
     return RET_OK;
}

int CChaletHomeServerInterface::UpdateChaletData(CChaletMainStatus *Data)
{
    QByteArray JsonByteArray;
    qint64 TimeStamp = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000;

    JsonByteArray.append(QString("{\"timestamp\":%1, ").arg(TimeStamp));
    JsonByteArray.append("\"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());

 //   qDebug("%s",qPrintable(JsonByteArray));

    mMQTTClient.publish(QString("chalet/telemetry"),JsonByteArray,0,true);
    return RET_OK;

}

int CChaletHomeServerInterface::ConnectToServer()
{
    //Setup the client before connecting.
    mMQTTClient.setAutoKeepAlive(true);
    mMQTTClient.setClientId("LeChalet");
    mMQTTClient.setHostname(MQTT_SERVER_IP);
    mMQTTClient.setPort(MQTT_SERVER_PORT);
    mMQTTClient.setPassword(MQTT_SERVER_PWD);
    mMQTTClient.setUsername(MQTT_SERVER_LOGIN);

    qDebug("Trying to connect Chalet MQTT client...");
    mMQTTClient.connectToHost();

    return RET_OK;
}

int CChaletHomeServerInterface::DisconnectFromServer()
{
    mMQTTClient.disconnectFromHost();
    return RET_OK;
}

void CChaletHomeServerInterface::MQTTClientError(QMqttClient::ClientError error)
{
    qDebug(qPrintable(QString("Erreur du client Chalet MQTT: %1").arg(error)));
}

void CChaletHomeServerInterface::StateChanged()
{
    switch(mMQTTClient.state())
    {
        case QMqttClient::Disconnected:
        {
            qDebug("Chalet MQTT client disconnected");
            mConnectionTimer->start(1000);
            mConnectionTimer->stop();
            break;
        }
        case QMqttClient::Connected:
        {
            qDebug("Chalet MQTT client connected!");
            mConnectionTimer->stop();
            break;
        }
        case QMqttClient::Connecting:
        {
            mConnectionTimer->start(20000);
            qDebug("Chalet MQTT client is connecting");
            break;
        }
    }
}

void CChaletHomeServerInterface::ConnectionTimerExpired()
{
    qDebug("connection timer expired");
    DisconnectFromServer();
    ConnectToServer();

    mConnectionTimer->start(15000);

}
