#include "DirParserThread.h"

#include "GlobalDefine.h"



void CDirParserThread::ParseDirectories()
{
    if(mRootDir.absolutePath().isEmpty() == true)
    {
        emit ParsingFinished(0);
        return;
    }

    ParseDir(mRootDir,mKeepData);

    emit ParsingFinished(1);
    qDebug("Worker thread finished");


}

CDirParserThread::CDirParserThread()
{
    mExecThread = true;
}

int CDirParserThread::ParseDir(QDir dir, bool KeepData)
{
    mMutex.lockForRead();
    bool Run = mExecThread;
    mMutex.unlock();
    if(Run == false)
        return 0;

    QStringList LogFilters;
    QFileInfoList list;
   // QString LogDataDir = mProgramHandle->GetLogDataPath();
    LogFilters << mFilter;//"*.bin";

    //Load files in base directory
    QDir LogDir(dir);
    LogDir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
    LogDir.setNameFilters(LogFilters);
    LogDir.setSorting(QDir::Name);
    list = LogDir.entryInfoList();
    if(list.size() != 0)
    {
        //Extract data for each passage
        for(int i = 0; i < list.size(); i++)
        {
            //ParseNewLog(list.at(i).filePath(),KeepData);
            unsigned int ret;
//            CLogElement *NewLog = CTrainLogFileMgr::instance()->OpenTrainLog(list.at(i).filePath(),ret);
//            if(ret == RET_OK)
            if(mFilter == "*.bin")
            {
                CLogElement *NewLog = CTrainLogFileMgr::instance()->OpenTrainLog(list.at(i).filePath(),ret);
                if(ret == RET_OK)
                {
                    emit NewLogParsed(NewLog);
                }
            }
            else
            {
                emit NewLogParsed(list.at(i).filePath(),KeepData);
            }
        }
    }
    else
    {
        emit EmptyDirParsed();
    }


    //Check for subdirectories
    QDir SubDirectories(dir);

    SubDirectories.setFilter(QDir::Dirs | QDir::NoDotAndDotDot);

    QFileInfoList SubDirList = SubDirectories.entryInfoList();
    for(int i = 0; i < SubDirList.size(); i++)
    {
        ParseDir(QDir(SubDirList.at(i).absoluteFilePath()), KeepData);
    }

    return 1;
}

void CDirParserThread::SetParsingInfo(QDir dir, QString Filter, bool KeepData)
{
    //qDebug("DirParserThread parsing info: dir: %s, Filter: %s",dir.dirName().toAscii().data(),Filter.toAscii().data());
    mRootDir = dir;
    mKeepData = KeepData;
    mFilter = Filter;
}

void CDirParserThread::KillThread()
{
    mMutex.lockForWrite();
    mExecThread = false;
    mMutex.unlock();
}
