#include "LogsHandler.h"
#include "LogsSorterConfigData.h"
#include "LogsSorter.h"
#include <QDir>
#include <QFileInfo>

CLogsHandler::CLogsHandler() : QObject()
{
    mSortingConfigData = 0;
    mProgramPtr = 0;

    mLogsWatcher = new QFileSystemWatcher();
    mHandlerRunning = false;

    connect(mLogsWatcher,&QFileSystemWatcher::directoryChanged,this,&CLogsHandler::WatchedDirectoryChanged);

}

CLogsHandler::~CLogsHandler()
{
    mLogsWatcher->removePaths(mLogsWatcher->directories());
    delete mLogsWatcher;
}

int CLogsHandler::SetSortingConfigData(CLogsSorterConfigData *ConfigData)
{
    mSortingConfigData = ConfigData;
    mLogsWatcher->removePaths(mLogsWatcher->directories());

    if(QDir(ConfigData->mLogsSourceDirectory).exists())
    {
        mLogsWatcher->addPath(ConfigData->mLogsSourceDirectory);
        QString msg = QString("La surveillance est débutée pour le répertoire source %1").arg(ConfigData->mLogsSourceDirectory);
        qDebug(qPrintable(msg));
         mProgramPtr->AddGeneralMsgTextRequest(msg,Qt::darkGreen);
    }
    else
    {
        QString msg = QString("Erreur, le répertoire source %1 n'existe pas").arg(ConfigData->mLogsSourceDirectory);
    }
    return RET_OK;
}

int CLogsHandler::StartLogHandling()
{
    mHandlerRunning = true;
    return RET_OK;
}

int CLogsHandler::StopLogHandling()
{
    mHandlerRunning = false;
    return RET_OK;
}

int CLogsHandler::ParseWatchedDirectory()
{
    return ParseWatchedDirectory(mSortingConfigData->mLogsSourceDirectory);
}

void CLogsHandler::WatchedDirectoryChanged(QString Path)
{
    ParseWatchedDirectory(Path);
}

int CLogsHandler::ParseWatchedDirectory(QString Path)
{
    QDir SourceDir(Path);
    QFileInfoList LogFiles = SourceDir.entryInfoList();
    const CLogsFilterData *Filter;

    for(int i = 0; i < LogFiles.size(); i++)
    {
        for(int j = 0; j < mSortingConfigData->mLogsFiltersList.size(); j++)
        {
            Filter = &mSortingConfigData->mLogsFiltersList[j];

            if(LogFiles.at(i).fileName().contains(Filter->mLogIdentificator) &&  //Le fichier contient le différentiateur comme ZT1, ZT2, BooleanData, etc.
               LogFiles.at(i).fileName().contains(Filter->mLogPrefix))            //ET le fichier contient le bon préfixe (identification de la station).
            {
                if(Filter->mFilterOperation == CLogsFilterData::LOG_FILTER_MOVE_OPERATION_TYPE)
                {
                    QString msg= QString("Filtre trouvé pour le fichier %1").arg(LogFiles.at(i).fileName());
                    qDebug(qPrintable(msg));

                    QString FullDestinationPath = Filter->mLogDestination;
                    QString DestFilename = LogFiles.at(i).fileName();
                    FullDestinationPath.append("\\");

                    DestFilename.remove(Filter->mLogPrefix);
                    FullDestinationPath.append(DestFilename);

                    if(!QDir(Filter->mLogDestination).exists()) //Créer le répertoire cible s'il n'exite pas déjà
                    {
                        QDir().mkdir(Filter->mLogDestination);
                    }

                    if(QFile::copy(LogFiles.at(i).absoluteFilePath(),FullDestinationPath))
                    {
                        QString msg = QString("Fichier %1 copié vers %2").arg(LogFiles.at(i).absoluteFilePath()).arg(FullDestinationPath);
                        qDebug(qPrintable(msg));
                        mProgramPtr->AddGeneralMsgTextRequest(msg);
                    }
                    else
                    {
                        QString msg = QString("Impossible de copier %1 vers %2 (le fichier existe-t-il déjà ???)").arg(LogFiles.at(i).absoluteFilePath()).arg(FullDestinationPath);
                        qDebug(qPrintable(msg));
                        mProgramPtr->AddGeneralMsgTextRequest(msg,Qt::red);
                    }

                    if(QFile::remove(LogFiles.at(i).absoluteFilePath()))
                    {
                         QString msg = QString("Fichier %1 effacé").arg(LogFiles.at(i).absoluteFilePath());
                         qDebug(qPrintable(msg));
                         mProgramPtr->AddGeneralMsgTextRequest(msg);
                    }
                    else
                    {
                         QString msg = QString("Impossible d'effacer le fichier %1").arg(LogFiles.at(i).absoluteFilePath());
                         qDebug(qPrintable(msg));
                         mProgramPtr->AddGeneralMsgTextRequest(msg,Qt::red);
                    }

                }
                else if(Filter->mFilterOperation == CLogsFilterData::LOG_FILTER_DELETE_OPERATION_TYPE)
                {
                    if(QFile::remove(LogFiles.at(i).absoluteFilePath()))
                    {
                         QString msg = QString("Fichier %1 effacé").arg(LogFiles.at(i).absoluteFilePath());
                         qDebug(qPrintable(msg));
                         mProgramPtr->AddGeneralMsgTextRequest(msg);
                    }
                    else
                    {
                         QString msg = QString("Impossible d'effacer le fichier %1").arg(LogFiles.at(i).absoluteFilePath());
                         qDebug(qPrintable(msg));
                         mProgramPtr->AddGeneralMsgTextRequest(msg);
                    }
                }
            }
        }

    }



    return RET_OK;
}
