#include "IspindelDevice.h"
#include <QJsonDocument>
#include <QJsonObject>

CIspindelDevice::CIspindelDevice()
{
    mISpindelServer = new QTcpServer;
    connect(mISpindelServer,SIGNAL(newConnection()),this,SLOT(IspindelClientConnected()));
    mISpindelServer->listen(QHostAddress::Any,95);

    mIspindelLog.clear();
    mDataLogger.LoadLogData(&mIspindelLog);

}

void CIspindelDevice::IspindelClientConnected()
{
    mIspindelClientConnection = mISpindelServer->nextPendingConnection();
    connect(mIspindelClientConnection,SIGNAL(readyRead()),this,SLOT(IspindelClientDataAvail()));
    qDebug("Ispindel connected");
}

void CIspindelDevice::IspindelClientDataAvail()
{
    CIspindelData *NewData = new CIspindelData;
    QByteArray IspindelData;
    if(mIspindelClientConnection->bytesAvailable() > 1)
    {
        IspindelData = QByteArray(mIspindelClientConnection->readAll());
    }
    else
    {
        return;
    }

    QJsonDocument JsonReply = QJsonDocument::fromJson(IspindelData);
    QJsonObject JsonObject = JsonReply.object();
    QStringList Keys = JsonObject.keys();
    if(Keys.isEmpty())
        return;

    NewData->mIspindelID = JsonObject["ID"].toInt();
    NewData->mRSSI = JsonObject["RSSI"].toInt();
    NewData->mAngle = JsonObject["angle"].toDouble();
    NewData->mBattery = JsonObject["battery"].toDouble();
    NewData->mGravity = JsonObject["gravity"].toDouble();
    NewData->mInterval = JsonObject["interval"].toInt();
    NewData->mIspindelName = JsonObject["name"].toString();
    NewData->mTemperatureUnits = JsonObject["temp_units"].toString();
    NewData->mTemperature = JsonObject["temperature"].toDouble();

    mIspindelLog.append(NewData);

    qDebug("ID : %i",NewData->mIspindelID);
    qDebug("RSSI : %i",NewData->mRSSI);
    qDebug("Angle : %f",NewData->mAngle);
    qDebug("Battery : %f",NewData->mBattery);
    qDebug("Gravity : %f",NewData->mGravity);
    qDebug("Interval (s): %i",NewData->mInterval);
    qDebug("Name : %s",qPrintable(NewData->mIspindelName));
    qDebug("Units : %s",qPrintable(NewData->mTemperatureUnits));
    qDebug("Temperature : %f",NewData->mTemperature);

    mDataLogger.WriteLogToFile(&mIspindelLog);
    emit NewIspindelDataReceived();


//    "ID"	6913415	QJsonValue (Number)
//    "RSSI"	-65	QJsonValue (Number)
//    "angle"	89.59756	QJsonValue (Number)
//    "battery"	4.301355	QJsonValue (Number)
//    "gravity"	33.36325	QJsonValue (Number)
//    "interval"	10	QJsonValue (Number)
//    "name"	"iSpindel001"	QJsonValue (String)
//    "temp_units"	"C"	QJsonValue (String)
//    "temperature"	20.625	QJsonValue (Number)


}

void CIspindelDevice::IspindelClientDisconnected()
{
    qDebug("Ispindel disconnected");
}

CIspindelDevice::~CIspindelDevice()
{
    mISpindelServer->close();
    for(int i = 0; i < mIspindelLog.size(); i++)
    {
        delete mIspindelLog[i];
        mIspindelLog.clear();
    }
}

CIspindelData *CIspindelDevice::GetLastestIspindelData()
{
    if(mIspindelLog.size() > 0)
        return mIspindelLog.last();
    else
        return 0;
}

QByteArray CIspindelDevice::GetAllDataBuffer()
{
    QByteArray Array;
    QDataStream Strm (&Array,QIODevice::WriteOnly | QIODevice::Unbuffered);

    int Size = mIspindelLog.size();

    Strm << Size;
    for(int i = 0; i < Size; i++)
    {
        Strm << *mIspindelLog.at(i);
    }

    return Array;
}

QByteArray CIspindelDevice::GetLastestIspindelDataBuffer()
{
    QByteArray Buf;
    if(mIspindelLog.size() > 1)
    {
        Buf= mIspindelLog.last()->ToByteArray();
    }
    return Buf;
}

bool CIspindelDevice::DeleteSampleRequest(int SampleIndex)
{
    if(SampleIndex >= mIspindelLog.size())
    {
        return false;
    }

    mIspindelLog.removeAt(SampleIndex);
    mDataLogger.WriteLogToFile(&mIspindelLog,false);

    return true;

}
