/****************************************************************************
**
** Copyright (C) 2014 Jolla Ltd.
** Contact: http://jolla.com/
**
** This file is part of Qt Creator.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Digia.
**
****************************************************************************/

#include "nxtbuildsteps.h"

#include <nxtconstants.h>
#include <qtc/nxtsdk.h>
#include <qtc/nxtsdkkitinformation.h>
#include <parser/nxtbundleparser.h>
#include <parser/nxtdeployparser.h>

#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/target.h>

using namespace ProjectExplorer;

namespace Nxt {
namespace Internal {

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

NxtSdkStartStep::NxtSdkStartStep(BuildStepList *bsl)
    : NxtAbstractVmStartStep(bsl, stepId())
{
    setDefaultDisplayName(displayName());
}

bool NxtSdkStartStep::init(QList<const BuildStep *> &earlierSteps)
{
    const NxtSdk *const nxtSdk = NxtSdkKitInformation::sdk(target()->kit());
    if (!nxtSdk) {
        addOutput(tr("Cannot start SDK: Missing IDS NXT Build Engine information in the kit"), OutputFormat::ErrorMessage);
        return false;
    }

    setConnection(nxtSdk->connection());

    return NxtAbstractVmStartStep::init(earlierSteps);
}

Core::Id NxtSdkStartStep::stepId()
{
    return Core::Id("Nxt.NxtSdkStartStep");
}

QString NxtSdkStartStep::displayName()
{
    return tr("Start IDS NXT Build Engine");
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//
// NxtBundleVisionAppStepConfigWidget
//

class NxtBundleStepConfigWidget : public SimpleBuildStepConfigWidget
{
    Q_OBJECT

public:
    NxtBundleStepConfigWidget(NxtBundleStep *step, QString command, QString arguments, QString buildDirectory)
        : SimpleBuildStepConfigWidget(step)
        , m_command(command)
        , m_arguments(arguments)
        , m_buildDirectory(buildDirectory)
    {
    }

    QString summaryText() const override
    {
        return QString::fromLatin1("<b>%1:</b> %2 %3 in %4").arg(displayName(), m_command, m_arguments, m_buildDirectory);
    }

private:
    const QString m_command;
    const QString m_arguments;
    const QString m_buildDirectory;
};

//
// NxtBundleVisionAppStep
//

const char BUILDSTEP_MAKE_NXTBUNDLE_ID[] = "Nxt.NxtBundleVisionAppStep";
const char BUILDSTEP_MAKE_NXTBUNDLE_DISPLAY_NAME[] = QT_TRANSLATE_NOOP("Nxt::Internal::NxtBundleVisionAppStep", "NXT Bundle");

const char BUILDSTEP_MAKE_NXTBUNDLE_BUILD_TARGETS_KEY[] = "Nxt.NxtBundleVisionAppStep.BuildTargets";
const char BUILDSTEP_MAKE_NXTBUNDLE_MAKE_ARGUMENTS_KEY[] = "Nxt.NxtBundleVisionAppStep.MakeArguments";
const char BUILDSTEP_MAKE_NXTBUNDLE_MAKE_COMMAND_KEY[] = "Nxt.NxtBundleVisionAppStep.MakeCommand";
const char BUILDSTEP_MAKE_NXTBUNDLE_CLEAN_KEY[] = "Nxt.NxtBundleVisionAppStep.Clean";

NxtBundleStep::NxtBundleStep(BuildStepList *parent, const QString &buildTarget)
    : AbstractProcessStep(parent, BUILDSTEP_MAKE_NXTBUNDLE_ID)
    , m_makeCommand(Constants::NXT_WRAPPER_MAKE)
    , m_makeArguments("nxtbundle")
{
    setDefaultDisplayName(QCoreApplication::translate("Nxt::Internal::NxtBundleVisionAppStep", BUILDSTEP_MAKE_NXTBUNDLE_DISPLAY_NAME));
    setBuildTarget(buildTarget, true);
}

bool NxtBundleStep::init(QList<const BuildStep *> &earlierSteps)
{
    BuildConfiguration *bc = buildConfiguration();
    if (!bc)
        bc = target()->activeBuildConfiguration();
    if (!bc)
        emit addTask(Task::buildConfigurationMissingTask());

    ToolChain *tc = ToolChainKitInformation::toolChain(target()->kit(), ProjectExplorer::Constants::CXX_LANGUAGE_ID);
    if (!tc)
        emit addTask(Task::compilerMissingTask());

    if (!bc || !tc) {
        emitFaultyConfigurationMessage();
        return false;
    }

    ProcessParameters *pp = processParameters();
    pp->setMacroExpander(bc->macroExpander());
    pp->setWorkingDirectory(bc->buildDirectory().toString());
    Utils::Environment env = bc->environment();

    // IDS_NXT_OCEAN NXT_FRAMEWORK
    //env.appendOrSet(QLatin1String(Constants::NXT_FRAMEWORK), kit->value("PE.Profile.SysRoot").toString());

    Utils::Environment::setupEnglishOutput(&env);
    pp->setEnvironment(env);
    pp->setCommand(makeCommand(bc->environment()));
    pp->setArguments(allArguments());
    pp->resolveAll();

    // If we are cleaning, then make can fail with an error code, but that doesn't mean
    // we should stop the clean queue
    // That is mostly so that rebuild works on an already clean project
    setIgnoreReturnValue(m_clean);

    setOutputParser(new NxtBundleParser());
    IOutputParser *parser = target()->kit()->createOutputParser();
    if (parser)
        appendOutputParser(parser);
    outputParser()->setWorkingDirectory(pp->effectiveWorkingDirectory());

    return AbstractProcessStep::init(earlierSteps);
}

void NxtBundleStep::setClean(bool clean)
{
    m_clean = clean;
}

bool NxtBundleStep::isClean() const
{
    return m_clean;
}

Core::Id NxtBundleStep::stepId()
{
    return Core::Id("Nxt.NxtBundleVisionAppStep");
}

QString NxtBundleStep::displayName()
{
    return BUILDSTEP_MAKE_NXTBUNDLE_DISPLAY_NAME;
}

QVariantMap NxtBundleStep::toMap() const
{
    QVariantMap map(AbstractProcessStep::toMap());

    map.insert(BUILDSTEP_MAKE_NXTBUNDLE_BUILD_TARGETS_KEY, m_buildTargets);
    map.insert(BUILDSTEP_MAKE_NXTBUNDLE_MAKE_ARGUMENTS_KEY, m_makeArguments);
    map.insert(BUILDSTEP_MAKE_NXTBUNDLE_MAKE_COMMAND_KEY, m_makeCommand);
    map.insert(BUILDSTEP_MAKE_NXTBUNDLE_CLEAN_KEY, m_clean);
    return map;
}

bool NxtBundleStep::fromMap(const QVariantMap &map)
{
    m_buildTargets = map.value(BUILDSTEP_MAKE_NXTBUNDLE_BUILD_TARGETS_KEY).toStringList();
    m_makeArguments = map.value(BUILDSTEP_MAKE_NXTBUNDLE_MAKE_ARGUMENTS_KEY).toString();
    m_makeCommand = map.value(BUILDSTEP_MAKE_NXTBUNDLE_MAKE_COMMAND_KEY).toString();
    m_clean = map.value(BUILDSTEP_MAKE_NXTBUNDLE_CLEAN_KEY).toBool();

    return BuildStep::fromMap(map);
}

QString NxtBundleStep::allArguments() const
{
    QString args = m_makeArguments;
    Utils::QtcProcess::addArgs(&args, m_buildTargets);
    return args;
}

QString NxtBundleStep::makeCommand(const Utils::Environment &environment) const
{
    QString command = m_makeCommand;
    if (command.isEmpty()) {
        ToolChain *tc = ToolChainKitInformation::toolChain(target()->kit(), ProjectExplorer::Constants::CXX_LANGUAGE_ID);
        if (tc)
            command = tc->makeCommand(environment);
        else
            command = "make";
    }
    return command;
}

void NxtBundleStep::run(QFutureInterface<bool> &fi)
{
    AbstractProcessStep::run(fi);
}

BuildStepConfigWidget *NxtBundleStep::createConfigWidget()
{
    return new NxtBundleStepConfigWidget(this, m_makeCommand, m_makeArguments, buildConfiguration()->buildDirectory().toUserOutput());
}

bool NxtBundleStep::immutable() const
{
    return false;
}

bool NxtBundleStep::buildsTarget(const QString &target) const
{
    return m_buildTargets.contains(target);
}

void NxtBundleStep::setBuildTarget(const QString &target, bool on)
{
    QStringList old = m_buildTargets;
    if (on && !old.contains(target))
         old << target;
    else if (!on && old.contains(target))
        old.removeOne(target);

    m_buildTargets = old;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#if 0 /* NxtDeployStep */
//
// NxtDeployVisionAppStepConfigWidget
//

class NxtDeployStepConfigWidget : public SimpleBuildStepConfigWidget
{
    Q_OBJECT

public:
    NxtDeployStepConfigWidget(NxtDeployStep *step, QString command, QString arguments, QString buildDirectory)
        : SimpleBuildStepConfigWidget(step)
        , m_command(command)
        , m_arguments(arguments)
        , m_buildDirectory(buildDirectory)
    {
    }

    QString summaryText() const override
    {
        return QString::fromLatin1("<b>%1:</b> %2 %3 in %4").arg(displayName(), m_command, m_arguments, m_buildDirectory);
    }

private:
    const QString m_command;
    const QString m_arguments;
    const QString m_buildDirectory;
};

//
// NxtDeployVisionAppStep
//

const char BUILDSTEP_MAKE_NxtDeploy_ID[] = "Nxt.NxtDeployVisionAppStep";
const char BUILDSTEP_MAKE_NxtDeploy_DISPLAY_NAME[] = QT_TRANSLATE_NOOP("Nxt::Internal::NxtDeployVisionAppStep", "NXT Deploy");

const char BUILDSTEP_MAKE_NXTDEPLOY_BUILD_TARGETS_KEY[] = "Nxt.NxtDeployVisionAppStep.BuildTargets";
const char BUILDSTEP_MAKE_NXTDEPLOY_MAKE_ARGUMENTS_KEY[] = "Nxt.NxtDeployVisionAppStep.MakeArguments";
const char BUILDSTEP_MAKE_NXTDEPLOY_MAKE_COMMAND_KEY[] = "Nxt.NxtDeployVisionAppStep.MakeCommand";
const char BUILDSTEP_MAKE_NXTDEPLOY_CLEAN_KEY[] = "Nxt.NxtDeployVisionAppStep.Clean";

NxtDeployStep::NxtDeployStep(BuildStepList *parent, const QString &buildTarget)
    : AbstractProcessStep(parent, BUILDSTEP_MAKE_NxtDeploy_ID)
    , m_makeCommand(Constants::NXT_WRAPPER_MAKE)
    , m_makeArguments("nxtdeploy")
{
    setDefaultDisplayName(QCoreApplication::translate("Nxt::Internal::NxtDeployVisionAppStep", BUILDSTEP_MAKE_NxtDeploy_DISPLAY_NAME));
    setBuildTarget(buildTarget, true);
}

bool NxtDeployStep::init(QList<const BuildStep *> &earlierSteps)
{
    BuildConfiguration *bc = buildConfiguration();
    if (!bc)
        bc = target()->activeBuildConfiguration();
    if (!bc)
        emit addTask(Task::buildConfigurationMissingTask());

    ToolChain *tc = ToolChainKitInformation::toolChain(target()->kit(), ProjectExplorer::Constants::CXX_LANGUAGE_ID);
    if (!tc)
        emit addTask(Task::compilerMissingTask());

    if (!bc || !tc) {
        emitFaultyConfigurationMessage();
        return false;
    }

    ProcessParameters *pp = processParameters();
    pp->setMacroExpander(bc->macroExpander());
    pp->setWorkingDirectory(bc->buildDirectory().toString());
    Utils::Environment env = bc->environment();
    Utils::Environment::setupEnglishOutput(&env);
    pp->setEnvironment(env);
    pp->setCommand(makeCommand(bc->environment()));
    pp->setArguments(allArguments());
    pp->resolveAll();

    // If we are cleaning, then make can fail with an error code, but that doesn't mean
    // we should stop the clean queue
    // That is mostly so that rebuild works on an already clean project
    setIgnoreReturnValue(m_clean);

    setOutputParser(new NxtDeployParser());
    IOutputParser *parser = target()->kit()->createOutputParser();
    if (parser)
        appendOutputParser(parser);
    outputParser()->setWorkingDirectory(pp->effectiveWorkingDirectory());

    return AbstractProcessStep::init(earlierSteps);
}

void NxtDeployStep::setClean(bool clean)
{
    m_clean = clean;
}

bool NxtDeployStep::isClean() const
{
    return m_clean;
}

Core::Id NxtDeployStep::stepId()
{
    return Core::Id("Nxt.NxtDeployVisionAppStep");
}

QString NxtDeployStep::displayName()
{
    return BUILDSTEP_MAKE_NxtDeploy_DISPLAY_NAME;
}

QVariantMap NxtDeployStep::toMap() const
{
    QVariantMap map(AbstractProcessStep::toMap());

    map.insert(BUILDSTEP_MAKE_NXTDEPLOY_BUILD_TARGETS_KEY, m_buildTargets);
    map.insert(BUILDSTEP_MAKE_NXTDEPLOY_MAKE_ARGUMENTS_KEY, m_makeArguments);
    map.insert(BUILDSTEP_MAKE_NXTDEPLOY_MAKE_COMMAND_KEY, m_makeCommand);
    map.insert(BUILDSTEP_MAKE_NXTDEPLOY_CLEAN_KEY, m_clean);
    return map;
}

bool NxtDeployStep::fromMap(const QVariantMap &map)
{
    m_buildTargets = map.value(BUILDSTEP_MAKE_NXTDEPLOY_BUILD_TARGETS_KEY).toStringList();
    m_makeArguments = map.value(BUILDSTEP_MAKE_NXTDEPLOY_MAKE_ARGUMENTS_KEY).toString();
    m_makeCommand = map.value(BUILDSTEP_MAKE_NXTDEPLOY_MAKE_COMMAND_KEY).toString();
    m_clean = map.value(BUILDSTEP_MAKE_NXTDEPLOY_CLEAN_KEY).toBool();

    return BuildStep::fromMap(map);
}

QString NxtDeployStep::allArguments() const
{
    QString args = m_makeArguments;
    Utils::QtcProcess::addArgs(&args, m_buildTargets);
    return args;
}

QString NxtDeployStep::makeCommand(const Utils::Environment &environment) const
{
    QString command = m_makeCommand;
    if (command.isEmpty()) {
        ToolChain *tc = ToolChainKitInformation::toolChain(target()->kit(), ProjectExplorer::Constants::CXX_LANGUAGE_ID);
        if (tc)
            command = tc->makeCommand(environment);
        else
            command = "make";
    }
    return command;
}

void NxtDeployStep::run(QFutureInterface<bool> &fi)
{
    AbstractProcessStep::run(fi);
}

BuildStepConfigWidget *NxtDeployStep::createConfigWidget()
{
    return new NxtDeployStepConfigWidget(this, m_makeCommand, m_makeArguments, buildConfiguration()->buildDirectory().toUserOutput());
}

bool NxtDeployStep::immutable() const
{
    return false;
}

bool NxtDeployStep::buildsTarget(const QString &target) const
{
    return m_buildTargets.contains(target);
}

void NxtDeployStep::setBuildTarget(const QString &target, bool on)
{
    QStringList old = m_buildTargets;
    if (on && !old.contains(target))
         old << target;
    else if (!on && old.contains(target))
        old.removeOne(target);

    m_buildTargets = old;
}
#endif /* NxtDeployStep */

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

} // namespace Internal
} // namespace Nxt

#include "nxtbuildsteps.moc"
