#include "IspindelInterface.h"
#include "ProtocolDefs.h"
#include "IspindelData.h"

CIspindelInterface::CIspindelInterface(int Address, CAbstractNetworkCommIF *NetworkInterface, CIspindelDevice *DevicePtr):
    CNetworkDevice(ID_ISPINDEL_INTERFACE,Address,NetworkInterface)
{
    mISpindelDevice = DevicePtr;
    connect(mISpindelDevice,SIGNAL(NewIspindelDataReceived()),this,SLOT(SendLastIspindelData()));
}

int CIspindelInterface::NewDeviceFrameReceived(int DeviceID, int DeviceAddress, int MessageID, int DataSize, QByteArray Data)
{
    Q_UNUSED(DeviceID)
    Q_UNUSED(DeviceAddress)
    Q_UNUSED(DataSize)
    Q_UNUSED(Data)

    switch(MessageID)
    {
        case ISPINDLE_LATEST_DATA_REQUEST:
        {
            QByteArray Buf;

            break;
        }
        case ISPINDEL_GET_FULL_DATA_BUFFER_REQUEST:
        {
            QByteArray Buf = mISpindelDevice->GetAllDataBuffer();
            mNetworkInterfacePtr->SendNetworkMessage(ID_ISPINDEL_INTERFACE,mDeviceAddress,ISPINDEL_GET_FULL_DATA_BUFFER_RESPONSE,Buf.size(),&Buf);
            break;
        }
        case ISPINDEL_DELETE_SAMPLE_REQUEST:
        {
            int Index;
            QDataStream Strm(&Data,QIODevice::ReadOnly | QIODevice::Unbuffered);
            Strm >> Index;
            bool Res = mISpindelDevice->DeleteSampleRequest(Index);

            QByteArray ResBuffer;
            QDataStream ResultStrm(&ResBuffer,QIODevice::WriteOnly | QIODevice::Unbuffered);
            ResultStrm << Res;

            mNetworkInterfacePtr->SendNetworkMessage(ID_ISPINDEL_INTERFACE,mDeviceAddress,ISPINDEL_DELETE_SAMPLE_RESPONSE,ResBuffer.size(),&ResBuffer);
            break;
        }
    }

    return RET_OK;
}

void CIspindelInterface::SendLastIspindelData()
{
    QByteArray Buf = mISpindelDevice->GetLastestIspindelDataBuffer();
    mNetworkInterfacePtr->SendNetworkMessage(ID_ISPINDEL_INTERFACE,mDeviceAddress,ISPINDLE_LATEST_DATA_RESPONSE,Buf.size(),&Buf);
    qDebug("Sent latest Ispindel data to interface");

}
