#include "ChaletUbidotsInterface.h"

CChaletUbidotsInterface::CChaletUbidotsInterface(QString UbidotsUsername, QObject *parent) : QObject(parent)
{
    mUbidotsUsername = UbidotsUsername;
//    mUbidotsPascalChaletClient = new QMqttClient(this);
//    mUbidotsPascalChaletClient->setHostname("things.ubidots.com");
//    mUbidotsPascalChaletClient->setPort(1883);
//    mUbidotsPascalChaletClient->setUsername("BBFF-tEq4lGAegEyP1H4EaYckNQ7ZHdZYzI");
//    mUbidotsPascalChaletClient->setPassword("12");
//    mUbidotsPascalChaletClient->connectToHost();

    mUbidotsChaletClient= new QMqttClient(this);
    mUbidotsChaletClient->setHostname(UBIDOTS_URL);
    mUbidotsChaletClient->setPort(UBIDOTS_PORT);
    mUbidotsChaletClient->setUsername(mUbidotsUsername);//"BBFF-tEq4lGAegEyP1H4EaYckNQ7ZHdZYzI");
    mUbidotsChaletClient->setPassword("12");

    connect(mUbidotsChaletClient,SIGNAL(stateChanged(ClientState)),this,SLOT(UbidotsStateChanged(ClientState)));

    mUbidotsChaletClient->connectToHost();
}

CChaletUbidotsInterface::~CChaletUbidotsInterface()
{
    mUbidotsChaletClient->disconnectFromHost();

    delete mUbidotsChaletClient;
}

int CChaletUbidotsInterface::LogUbidotsChaletData(CChaletMainStatus *Data)
{
    Q_UNUSED(Data)


    qDebug("LogUbidotsChaletData() should only be called from derived class...");


    return RET_OK;
}

void CChaletUbidotsInterface::UbidotsStateChanged(QMqttClient::ClientState state)
{
    qDebug("MQTT client %s is now in state %d",qPrintable(mInterfaceOwnerName),state);
    //MQTTStateChanged(state);
}






//////////////////////implementation
CChaletJFUbidotsInterface::CChaletJFUbidotsInterface(QString Username) : CChaletUbidotsInterface(Username)
{
    mInterfaceOwnerName = "J-F";
    //mUbidotsChaletClient->subscribe(QMqttTopicFilter("/v1.6/devices/ChaletDuino"))

    //connect(mInverterBtnSubscritption,SIGNAL(messageReceived(QMqttMessage)),this,SLOT(InverterBtnSubscriptionMsgReceived(QMqttMessage)));


    qDebug("JF Ubidots interface created");
}

int CChaletJFUbidotsInterface::LogUbidotsChaletData(CChaletMainStatus *Data)
{
    QString MQTTMsg = QString("{\"BattVoltage\": %1}").arg(Data->mBatteryVoltage);
    mUbidotsChaletClient->publish(QMqttTopicName("/v1.6/devices/ChaletDuino"),MQTTMsg.toUtf8());
    MQTTMsg.clear();
    MQTTMsg = QString("{\"InverterSwitch\": %1}").arg(Data->mWiFiModuleStatus !=0);
    mUbidotsChaletClient->publish(QMqttTopicName("/v1.6/devices/ChaletDuino"),MQTTMsg.toUtf8(),0,true);

    return RET_OK;
}

void CChaletJFUbidotsInterface::InverterBtnSubscriptionMsgReceived(QMqttMessage msg)
{
    qDebug("subscription msg.  Topic name: %s",qPrintable(msg.topic().name()));
}

void CChaletJFUbidotsInterface::WiFiBtnSubscriptionMsgReceived(QMqttMessage msg)
{

}

void CChaletJFUbidotsInterface::MQTTStateChanged(QMqttClient::ClientState)
{

}
