#include "logthread.h"
#include "yt_unit_shm.h"

extern YT_UNIT_SHM *ytShm;

LogThread::LogThread(QObject *parent) :
    QThread(parent)
{
    logList.clear();
    dbgList.clear();

}

void LogThread::appendLog(QString log)
{
    logList.append(log);
}

void LogThread::appendDbgLog(QString log)
{
    dbgList.append(log);
}

void LogThread::run()
{
    ytShm->dogTimeList.dogTime[LOG_THREAD].IDX = LOG_THREAD;
    ytShm->dogTimeList.dogTime[LOG_THREAD].WAITSEC = 30;
    ytShm->dogTimeList.dogTime[LOG_THREAD].ENABLED = 0x01;
    appendLog(QString("[%1] log thread start\r\n")
              .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")));
//            system("echo hello\n");
    while(1)
    {
        ytShm->dogTimeList.dogTime[LOG_THREAD].LASTFEED = QDateTime::currentDateTime().toTime_t();
        if(logList.length()>0)
        {
            QFile logfile(QString("log_%1.txt").arg(QDate::currentDate().toString("yyyyMMdd")));
            if(logfile.open(QIODevice::Append|QIODevice::Text|QIODevice::ReadWrite))
            {
                while(logList.length()>0){
                    logfile.write(logList.first().toUtf8());
                    logList.removeFirst();
                    usleep(10000);
                }
                logfile.close();
            }
        }
        if(dbgList.length()>0)
        {
            QFile dbgFile(QString("dbg_%1.txt").arg(QDate::currentDate().toString("yyyyMMdd")));
            if(dbgFile.open(QIODevice::Append|QIODevice::Text|QIODevice::ReadWrite))
            {
                while(dbgList.length()>0)
                {
                    dbgFile.write(dbgList.first().toUtf8());
                    dbgList.removeFirst();
                    usleep(10000);
                }
                dbgFile.close();
            }
        }
        usleep(500000);
    }
}
