#include "killprocessoperation.h"

#include <QProcess>

using namespace QInstaller;

static bool executeCommand(const QString &cmd)
{
    if (cmd.isEmpty())
        return -2; // The process cannot be started

    QProcess process;
    int ret = process.execute(cmd);
    return (ret != -1 && ret != -2);
}

KillProcessOperation::KillProcessOperation()
{
    setName(QLatin1String("KillProcess"));
}

void KillProcessOperation::backup()
{
}

bool KillProcessOperation::performOperation()
{
    const int argCount = arguments().count();
    if (argCount != 1 && argCount != 2) {
        setError(InvalidArguments);
        setErrorString(QString("Invalid arguments in %0: %1 arguments given, %2 expected%3.")
            .arg(name()).arg(argCount).arg(tr("1 or 2")));
        return false;
    }

    const QString cmdExecPath = argCount == 2
            ? arguments().at(0)
            : QString("cmd");
    const QString processName = arguments().at(argCount - 1);
    QString command;

#ifdef Q_OS_WIN
    command = QString("%1 /C taskkill /F /IM \"%2\" 2> nul")
            .arg(cmdExecPath)
            .arg(processName);
#endif
#ifdef Q_OS_MAC
    command = QString("pkill -9 \"%1\" 2> /dev/null")
            .arg(processName);
#endif
    return executeCommand(command);
}

bool KillProcessOperation::undoOperation()
{
    const QString processName = arguments().at(arguments().count() - 1);
    QString command;

#ifdef Q_OS_WIN
    const QString cmdExecPath = arguments().count() == 2
            ? arguments().at(0)
            : QString("cmd");
    command = QString("%1 /C taskkill /F /IM \"%2\" 2> nul")
            .arg(cmdExecPath)
            .arg(processName);
#endif
#ifdef Q_OS_MAC
    command = QString("pkill -9 \"%1\" 2> /dev/null")
            .arg(processName);
#endif
    return executeCommand(command);
}

bool KillProcessOperation::testOperation()
{
    return true;
}

Operation *KillProcessOperation::clone() const
{
    return new KillProcessOperation();
}
