// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#pragma once

#include "abi.h"
#include "toolchain.h"

#include <QFutureWatcher>

#include <utils/environment.h>

#include <optional>

namespace ProjectExplorer {

// --------------------------------------------------------------------------
// MsvcToolChain
// --------------------------------------------------------------------------

class PROJECTEXPLORER_EXPORT MsvcToolchain : public Toolchain
{
public:
    enum Type { WindowsSDK, VS };
    enum Platform { x86, amd64, x86_amd64, ia64, x86_ia64, arm, x86_arm, amd64_arm, amd64_x86,
                    x86_arm64, amd64_arm64, arm64, arm64_x86, arm64_amd64 };

    explicit MsvcToolchain(Utils::Id typeId);
    ~MsvcToolchain() override;

    bool isValid() const override;

    QString originalTargetTriple() const override;

    QStringList suggestedMkspecList() const override;
    Abis supportedAbis() const override;

    void toMap(Utils::Store &data) const override;
    void fromMap(const Utils::Store &data) override;

    bool hostPrefersToolchain() const override;
    void holdToolDetection(const IDevicePtr &device, quint64 token) override;

    MacroInspectionRunner createMacroInspectionRunner() const override;
    Utils::LanguageExtensions languageExtensions(const QStringList &cxxflags) const override;
    Utils::WarningFlags warningFlags(const QStringList &cflags) const override;
    Utils::FilePaths includedFiles(const QStringList &flags,
                              const Utils::FilePath &directoryPath) const override;
    BuiltInHeaderPathsRunner createBuiltInHeaderPathsRunner(
            const Utils::Environment &env) const override;
    void addToEnvironment(Utils::Environment &env) const override;

    Utils::FilePath makeCommand(const Utils::Environment &environment) const override;
    QList<Utils::OutputLineParser *> createOutputParsers() const override;
    bool isSameDevice(const Utils::FilePath &devicePath) const override;

    QString varsBatArg() const { return m_varsBatArg; }
    Utils::FilePath varsBat() const { return m_vcvarsBat; }
    void setupVarsBat(const Abi &abi, const Utils::FilePath &varsBat, const QString &varsBatArg);
    void resetVarsBat();
    Platform platform() const;
    QString platformName() const;

    bool operator==(const Toolchain &) const override;

    bool isJobCountSupported() const override { return false; }

    int priority() const override;

    static void cancelMsvcToolChainDetection();
    bool environmentInitialized() const { return !m_environmentModifications.isEmpty(); }

    using GenerateEnvResult = Utils::Result<Utils::EnvironmentItems>;

    static std::optional<MsvcToolchain::Platform> preferredPlatform(
        Utils::OsArch host, Utils::OsArch target);
    static bool archPrefersPlatform(Utils::OsArch host, MsvcToolchain::Platform platform);
    static bool archSupportsPlatform(Utils::OsArch host, MsvcToolchain::Platform platform);

protected:
    class WarningFlagAdder
    {
        int m_warningCode = 0;
        Utils::WarningFlags &m_flags;
        bool m_doesEnable = false;
        bool m_triggered = false;

    public:
        WarningFlagAdder(const QString &flag, Utils::WarningFlags &flags);
        void operator()(int warningCode, Utils::WarningFlags flagsSet);

        bool triggered() const;
    };

    static void inferWarningsForLevel(int warningLevel, Utils::WarningFlags &flags);

    Utils::Environment readEnvironmentSetting(const Utils::Environment &env) const;
    // Function must be thread-safe!
    virtual Macros msvcPredefinedMacros(const QStringList &cxxflags,
                                        const Utils::Environment &env) const;
    virtual Utils::LanguageVersion msvcLanguageVersion(const QStringList &cxxflags,
                                                       const Utils::Id &language,
                                                       const Macros &macros) const;
    bool canShareBundleImpl(const Toolchain &other) const override;

    void initEnvModWatcher(const QFuture<GenerateEnvResult> &future);

protected:
    mutable QMutex m_headerPathsMutex;
    mutable QHash<QStringList, HeaderPaths> m_headerPathsPerEnv;

private:
    void updateEnvironmentModifications(Utils::EnvironmentItems modifications);
    void handleEnvModResult();
    void rescanForCompiler();
    void rescanWhenDeviceReady();
    void releaseToolDetection();

    // Set while this toolchain keeps a device's tool detection open for its running capture.
    Utils::Id m_detectionDeviceId;
    quint64 m_detectionToken = 0;

    mutable Utils::EnvironmentItems m_environmentModifications;
    mutable QFutureWatcher<GenerateEnvResult> m_envModWatcher;
    QMetaObject::Connection m_deviceReadyConnection;

    mutable Utils::Environment m_lastEnvironment;   // Last checked 'incoming' environment.
    mutable Utils::Environment m_resultEnvironment; // Resulting environment for VC

protected:
    Utils::FilePath m_vcvarsBat;
    QString m_varsBatArg; // Argument
    mutable std::optional<bool> m_isValid;
};

class PROJECTEXPLORER_EXPORT ClangClToolchain : public MsvcToolchain
{
public:
    ClangClToolchain();

    bool isValid() const override;
    QStringList suggestedMkspecList() const override;
    void addToEnvironment(Utils::Environment &env) const override;
    Utils::FilePath compilerCommand() const override; // FIXME: Remove
    void setCompilerCommand(const Utils::FilePath &cmd) override { setClangPath(cmd); }
    QList<Utils::OutputLineParser *> createOutputParsers() const override;
    void toMap(Utils::Store &data) const override;
    void fromMap(const Utils::Store &data) override;
    BuiltInHeaderPathsRunner createBuiltInHeaderPathsRunner(
            const Utils::Environment &env) const override;

    const QList<MsvcToolchain *> &msvcToolchains() const;
    Utils::FilePath clangPath() const { return m_clangPath; }
    void setClangPath(const Utils::FilePath &path);

    Macros msvcPredefinedMacros(const QStringList &cxxflags,
                                const Utils::Environment &env) const override;
    Utils::LanguageVersion msvcLanguageVersion(const QStringList &cxxflags,
                                               const Utils::Id &language,
                                               const Macros &macros) const override;

    bool operator==(const Toolchain &) const override;

    int priority() const override;

private:
    bool canShareBundleImpl(const Toolchain &other) const override;

    Utils::FilePath m_clangPath;
};

void setupMsvcToolchain();
void setupClangClToolchain();

} // namespace ProjectExplorer
