#include "ChaletDataLogger.h"
#include <QDateTime>
#include <QString>
#include <QStringList>
#include <QDataStream>
#include <QFileInfo>



CChaletDataLogger::CChaletDataLogger(QObject *parent) : QObject(parent)
{
    mChaletLogFile = 0;
    OpenTodaysFile();
    mChaletNewLogFileTimer = new QTimer;
    connect(mChaletNewLogFileTimer,SIGNAL(timeout()),this,SLOT(NewLogFileTimerExpired()));
    mChaletNewLogFileTimer->setInterval(1000);
    mChaletNewLogFileTimer->setSingleShot(false);
    mChaletNewLogFileTimer->start();

}

int CChaletDataLogger::OpenTodaysFile()
{
    mTodaysDate = QDateTime::currentDateTime().date();
    bool create = false;
    QString LogFileName(CHALET_LORA_DATA_LOG_DIR);
    LogFileName.append("ChaletLora-");
    LogFileName.append(mTodaysDate.toString("yyyy-MM-dd"));
    LogFileName.append(".csv");

    if(mChaletLogFile != 0)
    {
        if(mChaletLogFile->isOpen())
        {
            mChaletLogFile->close();
        }
        mChaletLogFile->setFileName(LogFileName);
    }
    else
    {
        mChaletLogFile = new QFile(LogFileName);
    }

    //Check if today's file already exist, otherwise create it...
    if(QFile::exists(LogFileName) == false)
        create = true;

    if(mChaletLogFile->open(QIODevice::ReadWrite|QIODevice::Append|QIODevice::Unbuffered) == false)
    {
        delete mChaletLogFile;
        mChaletLogFile = 0;
        qDebug("Cannot open chalet LORA log file...");
        return RET_ERROR;
    }

    if(create)
    {
        qDebug("Creating new chalet LORA log file...");
        QString Header("Date;Heure;Courant Batterie;Tension Batterie;Inverter;Wifi\n");
        mChaletLogFile->write(qPrintable(Header));
        mChaletLogFile->flush();

    }
//    mChaletLogFile->close();

    qDebug("Chalet LORA log file created successfully");
    return RET_OK;
}

QByteArray *CChaletDataLogger::GetChaletData(QDate StartDate)
{

    if(StartDate > QDate::currentDate())
    {
        return 0;
    }

    QFile *LogFile =0;

    bool done = false;
    QByteArray WorkArray, *DataArray;
    DataArray = new QByteArray;
    int NbReadings = 0;
    DataArray->clear();

    while(!done)
    {

        if(StartDate > QDate::currentDate())
        {
            done = true;
            break;
        }
//        else if(StartDate == QDate::currentDate())
//        {
//            LogFile = mChaletLogFile;
//        }
        else
        {
            QString LogFileName(CHALET_LORA_DATA_LOG_DIR);
            LogFileName.append("ChaletLora-");
            LogFileName.append(StartDate.toString("yyyy-MM-dd"));
            LogFileName.append(".csv");

            if(QFileInfo::exists(LogFileName))
            {
                LogFile = new QFile(LogFileName);
                if(LogFile->open(QIODevice::ReadOnly|QIODevice::Unbuffered) == false)
                {
                    delete LogFile;
                    LogFile = 0;
                }
            }
            else
            {
                LogFile = 0;
            }
        }


//        if(mChaletLogFile == 0)
//        {
//            return 0;
//        }

//        if(mChaletLogFile->isOpen() == false)
//        {
//            return 0;
//        }

        if(LogFile != 0)
        {

            LogFile->seek(0);    //seek to the beginning of the log file
            WorkArray = LogFile->readLine(); //read and discard the header line.
            bool Finished = false;
            while(!Finished)
            {
                WorkArray.clear();
                WorkArray = LogFile->readLine();
                if(WorkArray.isEmpty())
                {
                    Finished = true;
                    break;
                }


                QStringList LineData = QString(WorkArray).remove("\n").split(QChar(';'));
                if(LineData.size() == 6) //if we don't have 6 parameters, something went very wrong
                { //"Date;Heure;Courant Batterie;Tension Batterie;Inverter;Wifi\n");

                    QString date = LineData.at(0);
                    //            QDate Date = QDate::fromString("yyyy-MM-dd",LineData.at(0));
                    QDate Date = QDate::currentDate();
                    Date = QDate::fromString(date,"yyyy-MM-dd");
                    QString time = LineData.at(1);
                    //            QTime Time = QTime::fromString("hh:mm:ss",LineData.at(1));
                    QTime Time = QTime::currentTime();
                    Time= QTime::fromString(time,"hh:mm:ss");
                    QDateTime DateTime(Date,Time);
//                    qDebug("Date: %s",qPrintable(Date.toString("yyyy-MM-dd")));
//                    qDebug("Time: %s",qPrintable(Time.toString("hh:mm:ss")));
//                    qDebug("Date Time: %s",qPrintable(DateTime.toString("yyyy-MM-dd-hh:mm:ss")));

                    //            time.setDate(QDate().fromString("yyyy-MM-dd",LineData.at(0)));
                    //            time.setTime(QTime().fromString("hh:mm:ss",LineData.at(1)));
                    QString temp = LineData.at(2);
                    bool OK;
                    qint16 BattCurrent = temp.toInt(&OK);
                    temp = LineData.at(3);
                    float BattVoltage = temp.toFloat(&OK);
                    temp = LineData.at(4);
                    quint8 InverterStatus = 0;
                    if(temp == "ON")
                    {
                        InverterStatus = 1;
                    }
                    temp = LineData.at(5);
                    quint8 WiFiStatus = 0;
                    if(temp == "ON")
                    {
                        WiFiStatus = 1;
                    }
                    CChaletMainStatus CurBlob;
                    CurBlob.mThisStatusDateTime = DateTime;
                    CurBlob.mBatteryCurrent = BattCurrent;
                    CurBlob.mBatteryVoltage = BattVoltage;
                    CurBlob.mInverterRelayStatus = InverterStatus;
                    CurBlob.mWiFiModuleStatus = WiFiStatus;

                    DataArray->append(CurBlob.ToByteArray());
                    NbReadings++;
                }
                else
                {
                    qDebug("Invalid nb. of parameters in today's data extraction");
                }


            }
        }


        if(LogFile != mChaletLogFile && LogFile != 0)
        {
            LogFile->close();
            delete LogFile;
        }
        LogFile = 0;
        StartDate = StartDate.addDays(1);

    }

    QByteArray Readings;
    QDataStream strm(&Readings,QIODevice::WriteOnly);
    strm.device()->seek(0);
    strm << NbReadings;
    DataArray->prepend(Readings);

    return DataArray;   //Don't forget to delete!!!
}

QByteArray *CChaletDataLogger::GetTodaysData()
{
    return GetChaletData(QDate::currentDate());
}


CChaletDataLogger::~CChaletDataLogger()
{
    if(mChaletLogFile)
    {
        mChaletLogFile->close();
        delete mChaletLogFile;
    }

}

bool CChaletDataLogger::LogChaletLORAData(CChaletMainStatus *Data)
{
    if(mChaletLogFile == 0)
    {
        qDebug("Invalid LORA log file handle");
        return false;
    }

//    if(mChaletLogFile->open(QIODevice::ReadWrite|QIODevice::Append|QIODevice::Text) == false)
//    {
//        delete mChaletLogFile;
//        mChaletLogFile = 0;
//        qDebug("Cannot open chalet LORA log file...");
//        return false;
//    }

    QString CSVData;// = QString("%1;%2;%3;%4;%5;%6\n").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd").arg(QDateTime::currentDateTime().toString("hh:mm:ss")).arg(Data->mBatteryCurrent).arg(Data->mBatteryVoltage).arg(Data->mInverterRelayStatus).arg(Data->mWiFiModuleStatus));
    CSVData.clear();
    CSVData.append(QDateTime::currentDateTime().toString("yyyy-MM-dd"));
    CSVData.append(";");
    CSVData.append(QDateTime::currentDateTime().toString("hh:mm:ss"));
    CSVData.append(";");
    CSVData.append(QString("%1;").arg(Data->mBatteryCurrent));
    CSVData.append(QString("%1;").arg(Data->mBatteryVoltage));
    if(Data->mInverterRelayStatus == 1)
        CSVData.append(QString("ON;"));
    else
        CSVData.append(QString("OFF;"));

    //CSVData.append(QString("%1;").arg(Data->mInverterRelayStatus));
    if(Data->mWiFiModuleStatus == 0)
        CSVData.append(QString("OFF\n"));
    else
        CSVData.append(QString("ON\n"));
   // CSVData.append(QString("%1\n").arg(Data->mWiFiModuleStatus));




    mChaletLogFile->write(qPrintable(CSVData));
    mChaletLogFile->flush();




  //  mChaletLogFile->close();

    return true;
}



void CChaletDataLogger::NewLogFileTimerExpired()
{
    if(QDateTime::currentDateTime().date() > mTodaysDate)    //If it's midnight...
    {
        qDebug("It's midnight... creating today's file...");
        OpenTodaysFile();
    }
}
