/**
 * Copyright (C) 2023-2026 Linaro Limited (or its affiliates). All rights reserved.
 * Copyright (C) 2012-2023 Arm Limited (or its affiliates).
 * All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 */

#include <QtGlobal>
#include "terminalprocess.h"
#include "terminal.h"
#include "terminalutil.h"

TerminalProcess::TerminalProcess(Terminal *terminal, QObject *parent) :
    QProcess(parent),
    mTerminal(terminal)
{
    mTerminal->setProcess(this);
    connect(this, qOverload<int, QProcess::ExitStatus>(&TerminalProcess::finished), this, &TerminalProcess::processFinished);
#if !defined (Q_OS_WIN)          // +explicit-local
#if QT_VERSION >= QT_VERSION_CHECK(6,0,0)
    setChildProcessModifier([this](){this->modifyChildProcess();});
#endif
#endif
}

TerminalProcess::~TerminalProcess()
{
    mTerminal->setProcess(0);
}

Terminal *TerminalProcess::terminal() const
{
    return mTerminal;
}

void TerminalProcess::start(const QString& program, const QStringList& arguments, OpenMode mode)
{
#if defined (Q_OS_WIN)          // +explicit-local
    mTerminal->emitProcessStarted(qt_create_commandline(program, arguments));
#else
    if (arguments.isEmpty())
    {
        mTerminal->emitProcessStarted(program);
    }
    else
    {
        mTerminal->emitProcessStarted(program + ' ' + arguments.join(" "));
    }
#endif
    QProcess::start(program, arguments, mode);
}

/**
 * Start a process from a script.
 *
 * For *nixes, this does the same as @c start().  For Windows, the sript is started with <tt>CMD.EXE /C</tt>.
 *
 * @param script The file name of the script.
 * @param arguments The arguments to be passed to the script.
 * @param mode The mode for communicating with the process.
 */
void TerminalProcess::startScript(const QString& script, const QStringList& arguments, const OpenMode mode)
{
#if defined (Q_OS_WIN)          // +explicit-local
    const QString command = QLatin1String("CMD.EXE");
    const QString args = QLatin1String("/Q /C \" ") + qt_create_commandline(script, arguments) + QLatin1String(" \"");
    mTerminal->emitProcessStarted(QLatin1String("%1 %2").arg(command, args));
    setProgram(command);
    setNativeArguments(args);
    QProcess::start(mode);
#else
    start(script, arguments, mode);
#endif
}

void TerminalProcess::processFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
    mTerminal->emitProcessFinished(exitCode, exitStatus);
}
