#include "IspindelDataLogger.h"
#include <QFile>
#include <QDataStream>
#include <GlobalDefine.h>

CIspindelDataLogger::CIspindelDataLogger(QObject *parent) : QObject(parent)
{

}

int CIspindelDataLogger::WriteLogToFile(QList<CIspindelData *> *Data, bool OnlyLastItem)
{
    QFile *LogFile;
    QString LogFileName(ISPINDEL_LOG_DIR);
    LogFileName.append("BrewLog");
    LogFileName.append(".blg");

    LogFile = new QFile(LogFileName);

    if(LogFile->open(QIODevice::ReadWrite|QIODevice::Unbuffered) == false)
    {
        delete LogFile;
        qDebug("Cannot open Ispindel log file for writing...");
        return RET_ERROR;
    }

    QDataStream Strm(LogFile);

    //Write header

    int FileVer = ISPINDEL_LOG_FILE_VERSION;
    int NbItems = Data->size();
    LogFile->seek(0);

    Strm << FileVer << NbItems;

    if(OnlyLastItem)
    {
        //seek to the end of the file
        LogFile->seek(LogFile->size());

        //write the last item
        Strm << *Data->last();
    }
    else
    {
        for(int i = 0; i < Data->size(); i++)
        {
            Strm << *Data->at(i);
        }
    }

    LogFile->close();
    delete LogFile;

    return RET_OK;

}

int CIspindelDataLogger::LoadLogData(QList<CIspindelData *> *DataList)
{
    QFile *LogFile;
    QString LogFileName(ISPINDEL_LOG_DIR);
    LogFileName.append("BrewLog");
    LogFileName.append(".blg");

    LogFile = new QFile(LogFileName);

    if(LogFile->open(QIODevice::ReadOnly|QIODevice::Unbuffered) == false)
    {
        delete LogFile;
        qDebug("Cannot open Ispindel log file for loading...");
        return RET_ERROR;
    }

    QDataStream Strm(LogFile);
    DataList->clear();

    int FileVersion, NbItems;
    Strm >> FileVersion;
    Strm >> NbItems;

    for(int i = 0; i < NbItems; i++)
    {
        CIspindelData *Data = new CIspindelData;
        Strm >> *Data;
        DataList->append(Data);
    }

    LogFile->close();
    delete LogFile;

    qDebug("Ispindel loaded %d readings",DataList->size());
    for(int i = 0; i < DataList->size(); i++)
    {
        qDebug(qPrintable(DataList->at(i)->mSampleDateTime.toString("yyyy-MM-dd hh:mm:ss")));
    }

    return RET_OK;


}
