#include "SFTPServerManager.h"
#include "GlobalDefine.h"
#include <QFile>
#include "EngLog.h"


CSFTPServerManager::CSFTPServerManager()
{
    mEnableSFTPClient = false;
}

int CSFTPServerManager::InitFTPServerManager(bool EnableSFTPClient, QString SFTPLogin, QString SFTPPassword, QString SFTPServerAddress, QString SFTPRemoteDir, QString FilenamePrefix, bool CopyEngLog)
{
    if(EnableSFTPClient == false)
    {
        mEnableSFTPClient = false;
        return RET_OK;
    }

    mEnableSFTPClient = true;
    mSFTPLogin = SFTPLogin;
    mSFTPPassword = SFTPPassword;
    mSFTPServerAddress = SFTPServerAddress;
    mSFTPRemoteDir = SFTPRemoteDir;
    mFilenamePrefix = FilenamePrefix;
    mCopyEngLog = CopyEngLog;

    mProcessTimer = new QTimer;
    mProcessTimer->setSingleShot(true);
    connect(mProcessTimer,SIGNAL(timeout()),this,SLOT(ProcessTimerExpired()));

    mTransferProcess = new QProcess(this);
    connect(mTransferProcess,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(ProcessFinished(int,QProcess::ExitStatus)));

    QFile *PWDFile = new QFile("./password");
    if(PWDFile->open(QFile::ReadWrite | QFile::Truncate | QFile::Text | QFile::Unbuffered) == false)
    {
        CEngLog::instance()->AddLogString(QString("Gestionnaire de client SFTP: Impossible de mettre à jour le password dans le fichier"));
        PWDFile->close();
        delete PWDFile;
    }

    PWDFile->write(qPrintable(SFTPPassword));
    PWDFile->close();
    delete PWDFile;

    CEngLog::instance()->AddLogString(QString("Gestionnaire de client SFTP initialisé."));

    return RET_OK;
}

CSFTPServerManager::~CSFTPServerManager()
{
    delete mTransferProcess;
    delete mProcessTimer;
}

int CSFTPServerManager::TransferTrainLogToSFTPServer(QString FileName, bool Detection)
{
    if(mEnableSFTPClient == false)
    {
        return RET_ERROR;
    }
    if(mTransferProcess->state() != QProcess::NotRunning)
    {
        CEngLog::instance()->AddLogString("Copie de fichier log avortée car QProcess roule");
        return RET_ERROR;
    }


    QString DestFilePath = FileName;
    if(Detection == true)
    {
       DestFilePath.prepend(mFilenamePrefix + "-D-"); //Flag indiquant que ce passage contient des détections (D)
    }
    else
    {
        DestFilePath.prepend(mFilenamePrefix + "-N-"); //Flag inidiquant un passage normal (sans détection) (N)
    }


    DestFilePath.prepend(mSFTPRemoteDir);
    QString OriginFilePath = FileName;
    OriginFilePath.prepend("./Trains/");

    QString Cmd;

#ifdef USE_SCP
    Cmd = QString ("sshpass -p \"%1\" scp %2 %3@%4:%5").arg(mSFTPPassword).arg(OriginFilePath).arg(mSFTPLogin).arg(mSFTPServerAddress).arg(DestFilePath);
#else
    QFile *SFTPBatchFile = new QFile("./sftpbatch");
    if(SFTPBatchFile->open(QFile::ReadWrite | QFile::Truncate | QFile::Text | QFile::Unbuffered) == false)
    {
       // qDebug("Imposible d'ouvrir le fichier sftpbatch");
        SFTPBatchFile->close();
        delete SFTPBatchFile;
        return RET_ERROR;
    }

    QString BatchCmds;
    BatchCmds.clear();

    BatchCmds.append(QString("put %1 %2\n").arg(OriginFilePath).arg(DestFilePath));
    QString DestLogFileName = QString("%1%2-LogZT.txt").arg(mSFTPRemoteDir).arg(mFilenamePrefix);
    BatchCmds.append(QString("put ./LOG/LogZT.txt %1").arg(DestLogFileName));
    if(mCopyEngLog == true)
    {
        DestLogFileName = QString("%1%2-IngLog.txt").arg(mSFTPRemoteDir).arg(mFilenamePrefix);
        BatchCmds.append(QString("\n"));
        BatchCmds.append(QString("put ./ING/IngLog.txt %1").arg(DestLogFileName));
    }

    SFTPBatchFile->write(qPrintable(BatchCmds));
    SFTPBatchFile->close();
    delete SFTPBatchFile;

    //Cmd = QString ("sshpass -f ./password sftp -oBatchMode=no -b ./sftpbatch %1@%2").arg(mSFTPLogin).arg(mSFTPServerAddress);
    Cmd = QString ("sshpass -f ./password sftp -oStrictHostKeyChecking=no -oBatchMode=no -b ./sftpbatch %1@%2").arg(mSFTPLogin).arg(mSFTPServerAddress);


#endif

    CEngLog::instance()->AddLogString(QString("Commande pour copie du fichier log: %1").arg(Cmd),3);



    mTransferProcess->start(Cmd);
    mProcessTimer->start(SFTP_PROCESS_TIMEOUT);  //Allow some time to copy the file


    return RET_OK;
}

void CSFTPServerManager::NewTrainFileSaved(QString Filename, bool Detection)
{
    TransferTrainLogToSFTPServer(Filename,Detection);
}

void CSFTPServerManager::ProcessFinished(int ExitCode, QProcess::ExitStatus ExitStatus)
{
    CEngLog::instance()->AddLogString(QString("Process SFTP terminé.  Exit code: %1 || Exit status: %2 || Output: %3 || Erreur: %4 || stdout: %5").arg(ExitCode).arg(ExitStatus).arg(qPrintable(mTransferProcess->readAllStandardOutput())).arg(qPrintable(mTransferProcess->readAllStandardError())).arg(qPrintable(mTransferProcess->readAll())));
    mProcessTimer->stop();
    // qDebug("stdout: %s",qPrintable(mTransferProcess->readAll()));
}

void CSFTPServerManager::ProcessTimerExpired()
{
    if(mTransferProcess->state() != QProcess::NotRunning)
    {
        mTransferProcess->terminate();
        CEngLog::instance()->AddLogString(QString("Timer du process SFTP expiré Output: %1 || Erreur: %2").arg(qPrintable(mTransferProcess->readAllStandardOutput())).arg(qPrintable(mTransferProcess->readAllStandardError())),2);
    }
}
