/*****************************************************************************
 * $CAMITK_LICENCE_BEGIN$
 *
 * CamiTK - Computer Assisted Medical Intervention ToolKit
 * (c) 2001-2025 Univ. Grenoble Alpes, CNRS, Grenoble INP - UGA, TIMC, 38000 Grenoble, France
 *
 * Visit http://camitk.imag.fr for more information
 *
 * This file is part of CamiTK.
 *
 * CamiTK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * CamiTK is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with CamiTK.  If not, see <http://www.gnu.org/licenses/>.
 *
 * $CAMITK_LICENCE_END$
 ****************************************************************************/

#include <QTextStream>
#include <QThread>

#include "ElastixRunner.h"

// --------------- constructor -------------------
ElastixRunner::ElastixRunner(QString elastixPath, QStringList arguments, QString workingDirectory, QObject* parent) : QObject(parent) {
    program = elastixPath;
    this->arguments = arguments;

    if (arguments[0] == "--version") {
        timeOut = 5000;  // 5 seconds timeout
    }
    else {
        timeOut = -1;  // blocking process by default
        this->workingDirectory = workingDirectory;
    }
}

// --------------- startProcess (slot) -------------------
void ElastixRunner::startProcess() {
    QProcess process;
    process.setWorkingDirectory(workingDirectory);
    process.setProcessChannelMode(QProcess::MergedChannels);

    // redirect stdout
    connect(&process, &QProcess::readyReadStandardOutput, this, &ElastixRunner::processOutput);

    process.start(program, arguments);
    bool started = process.waitForStarted();
    if (started && !process.waitForFinished(timeOut)) {
        exitCode = process.exitCode();
        processError = process.error();
        process.kill();
    }

    processError = process.error();
    exitCode = process.exitCode();
}

// --------------- processOutput (slot) -------------------
void ElastixRunner::processOutput() {
    QProcess* process = qobject_cast<QProcess*>(sender());
    if (process) {
        QTextStream stream(process);
        while (!stream.atEnd()) {
            QString line = stream.readLine();
            output.append(line + "\n");
            emit outputReady(line);
        }
    }
}

// --------------- getExitCode -------------------
int ElastixRunner::getExitCode() const {
    return exitCode;
}

// --------------- getStdOutput -------------------
QString ElastixRunner::getStdOutput() const {
    return output;
}


// --------------- getProcessError -------------------
QString ElastixRunner::getProcessError() const {
    switch (processError) {
        case QProcess::FailedToStart:
            return "The process failed to start. Either the invoked program is missing, or you may have insufficient permissions or resources to invoke the program.";
        case QProcess::Crashed:
            return "The process crashed some time after starting successfully.";
        case QProcess::Timedout:
            return "The process timed out.";
        case QProcess::WriteError:
            return "An error occurred when attempting to write to the process. For example, the process may not be running, or it may have closed its input channel.";
        case QProcess::ReadError:
            return "An error occurred when attempting to read from the process. For example, the process may not be running.";
        case QProcess::UnknownError:
        default:
            return "";
    }
}