// 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 "../projectexplorer_export.h"
#include "filetransferinterface.h"
#include "idevicefwd.h"

#include <QtTaskTree/QTaskTree>

#include <utils/aspects.h>
#include <utils/filepath.h>
#include <utils/hostosinfo.h>
#include <utils/id.h>
#include <utils/portlist.h>
#include <utils/result.h>
#include <utils/store.h>

#include <QAbstractSocket>
#include <QCoreApplication>
#include <QList>
#include <QObject>
#include <QUrl>

#include <functional>

QT_BEGIN_NAMESPACE
class QPixmap;
class QWidget;
QT_END_NAMESPACE

namespace Utils {
class CommandLine;
class DeviceFileAccess;
class Environment;
class PortList;
class Port;
class Process;
class ProcessInterface;
} // Utils

namespace Layouting { class Layout; }

namespace ProjectExplorer {

class DeviceConstRef;
class FileTransferInterface;
class FileTransferSetupData;
class Kit;
class Project;
class SshParameters;
class SshParametersAspectContainer;
class Target;
class Task;

namespace Internal { class IDevicePrivate; }

class IDeviceWidget;
class DeviceTester;

class PROJECTEXPLORER_EXPORT DeviceToolAspect : public Utils::FilePathAspect
{
public:
    enum ToolType {
        RunTool = 1,     // Tool used in connection with project running (on target device)
        BuildTool = 2,   // Tool used in connection with project building (on build device)
        SourceTool = 4,  // Tool used on project sources (typically, but not necessarily build device)
        AllTools = RunTool | BuildTool | SourceTool
    };

    using Utils::FilePathAspect::FilePathAspect;

    void addToLayoutImpl(Layouting::Layout &parent) override;

    Utils::Id toolId() const;
    ToolType toolType() const;

    void setToolId(const Utils::Id toolId);
    void setToolType(ToolType toolType);

public:
    Utils::Id m_toolId;
    ToolType m_toolType = AllTools;
};

class PROJECTEXPLORER_EXPORT DeviceToolAspectFactory
{
public:
    DeviceToolAspectFactory();
    ~DeviceToolAspectFactory();

    DeviceToolAspect *createAspect(const DeviceConstRef &device) const;

    Utils::Id toolId() const;
    QStringList filePattern() const;
    Utils::Result<> check(const DeviceConstRef &device, const Utils::FilePath &) const;

protected:
    using Checker = std::function<Utils::Result<>(const DeviceConstRef &device, const Utils::FilePath &)>;
    void setToolId(const Utils::Id &toolId);
    void setFilePattern(const QStringList &filePattern);
    void setLabelText(const QString &labelText);
    void setToolTip(const QString &toolTip);
    void setVariablePrefix(const QByteArray &variablePrefix);
    void setChecker(const Checker &checker);
    void setToolType(DeviceToolAspect::ToolType toolType);

private:
    void autoDetect(const DeviceConstRef &device, const Utils::FilePaths &searchPaths);

    Utils::Id m_toolId;
    QString m_labelText;
    QString m_toolTip;
    QStringList m_filePattern;
    QByteArray m_variablePrefix;
    Checker m_checker;
    DeviceToolAspect::ToolType m_toolType = DeviceToolAspect::AllTools;
};

enum class SignalOperationMode
{
    KillByPath,
    KillByPid,
    InterruptByPid
};

class PROJECTEXPLORER_EXPORT SignalOperationData
{
public:
    SignalOperationMode mode = SignalOperationMode::KillByPath;
    Utils::FilePath filePath = {};
    qint64 pid = 0;
    Utils::FilePath debuggerPath = {}; // Used only for Win / Desktop.

    Utils::Result<> isValid() const;
};

// See cpp file for documentation.
class PROJECTEXPLORER_EXPORT IDevice
        : public Utils::AspectContainer, public std::enable_shared_from_this<IDevice>
{
    friend class Internal::IDevicePrivate;
public:
    using Ptr = IDevicePtr;
    using ConstPtr = IDeviceConstPtr;

    enum Origin { ManuallyAdded, AutoDetected, AddedBySdk };
    enum MachineType { Hardware, Emulator };

    virtual ~IDevice();

    QString displayName() const;
    void setDisplayName(const QString &name);

    QString defaultDisplayName() const;
    void setDefaultDisplayName(const QString &name);

    void addDisplayNameToLayout(Layouting::Layout &layout) const;

    // Provide some information on the device suitable for formated
    // output, e.g. in tool tips. Get a list of name value pairs.
    class DeviceInfoItem {
    public:
        DeviceInfoItem(const QString &k, const QString &v) : key(k), value(v) { }

        QString key;
        QString value;
    };
    using DeviceInfo = QList<DeviceInfoItem>;
    virtual DeviceInfo deviceInformation() const;

    Utils::Id type() const;
    void setType(Utils::Id type);

    bool isAutoDetected() const;
    bool isFromSdk() const;
    Utils::Id id() const;

    virtual QList<Task> validate() const;

    QString displayType() const;
    Utils::OsType osType() const;

    virtual IDeviceWidget *createWidget() = 0;

    struct DeviceAction
    {
        DeviceAction(const QString &display,
                     const std::function<void(const IDevice::Ptr &)> &execute,
                     const std::function<bool(const IDevice::ConstPtr &)> &activeChecker = {})
            : display(display), execute(execute), activeChecker(activeChecker)
        {}

        QString display;
        std::function<void(const IDevice::Ptr &device)> execute;
        std::function<bool(const IDevice::ConstPtr &device)> activeChecker;
    };
    void addDeviceAction(const DeviceAction &deviceAction);
    const QList<DeviceAction> deviceActions() const;

    virtual QtTaskTree::ExecutableItem portsGatheringRecipe(
        const QtTaskTree::Storage<Utils::PortsOutputData> &output) const;
    virtual bool canCreateProcessModel() const { return false; }
    virtual bool hasDeviceTester() const { return false; }
    virtual DeviceTester *createDeviceTester();
    void setIsTesting(bool isTesting);
    bool isTesting() const;

    virtual bool canMount(const Utils::FilePath &filePath) const;

    virtual QtTaskTree::ExecutableItem signalOperationRecipe(
        const SignalOperationData &data,
        const QtTaskTree::Storage<Utils::Result<>> &resultStorage) const;

    enum DeviceState { DeviceReadyToUse, DeviceConnected, DeviceDisconnected, DeviceStateUnknown };
    DeviceState deviceState() const;
    void setDeviceState(const DeviceState state);
    virtual QString deviceStateToString() const;
    virtual QPixmap deviceStateIcon() const;

    QIcon overlayIcon() const;

    static Utils::Id typeFromMap(const Utils::Store &map);
    static Utils::Id idFromMap(const Utils::Store &map);

    static QString defaultPrivateKeyFilePath();
    static QString defaultPublicKeyFilePath();

    SshParameters sshParameters() const;
    void setDefaultSshParameters(const SshParameters &sshParameters);

    SshParametersAspectContainer &sshParametersAspectContainer() const;

    enum ControlChannelHint { QmlControlChannel };
    virtual QUrl toolControlChannel(const ControlChannelHint &) const;

    Utils::PortList freePorts() const;
    void setFreePorts(const Utils::PortList &freePorts);

    MachineType machineType() const;
    void setMachineType(MachineType machineType);

    virtual Utils::FilePath rootPath() const;
    virtual Utils::FilePath filePath(const QString &pathOnDevice) const;

    static Utils::FilePath deviceToolPath(Utils::Id toolId, const Utils::FilePath &deviceHint);
    Utils::FilePath deviceToolPath(Utils::Id toolId) const;
    QList<DeviceToolAspect *> deviceToolAspects(DeviceToolAspect::ToolType supportType) const;

    std::function<void(Layouting::Layout *)> deviceToolsGui();

    void setExtraData(Utils::Id kind, const QVariant &data);
    QVariant extraData(Utils::Id kind) const;

    void setupId(Origin origin, Utils::Id id = Utils::Id());

    bool canOpenTerminal() const;
    void openTerminal(const Utils::Environment &env,
                      const Utils::FilePath &workingDir,
                      const Utils::Continuation<> &cont = {}) const;

    bool isWindowsDevice() const { return osType() == Utils::OsTypeWindows; }
    bool isLinuxDevice() const { return osType() == Utils::OsTypeLinux; }
    bool isMacDevice() const { return osType() == Utils::OsTypeMac; }
    bool isAnyUnixDevice() const;

    Utils::DeviceFileAccessPtr fileAccess() const;
    bool supportsFileAccess() const;
    virtual void tryToConnect(const Utils::Continuation<> &cont) const;
    virtual Utils::Result<> handlesFile(const Utils::FilePath &filePath) const;

    virtual Utils::FilePath searchExecutableInPath(const QString &fileName) const;
    virtual Utils::FilePath searchExecutable(const QString &fileName,
                                             const Utils::FilePaths &dirs) const;

    virtual Utils::ProcessInterface *createProcessInterface() const;
    virtual FileTransferInterface *createFileTransferInterface(
            const FileTransferSetupData &setup) const;
    bool supportsFileTransferMethod(FileTransferMethod method) const;

    Utils::Environment systemEnvironment() const;
    virtual Utils::Result<Utils::Environment> systemEnvironmentWithError() const;

    virtual void aboutToBeRemoved() const {}

    virtual Utils::Result<> ensureReachable(const Utils::FilePath &other) const;
    virtual Utils::Result<Utils::FilePath> localSource(const Utils::FilePath &other) const;

    virtual bool prepareForBuild(const Target *target);

    virtual void checkOsType() {}

    void doApply() const;

    virtual bool supportsQtTargetDeviceType(const QSet<Utils::Id> &targetDeviceTypes) const;

    Utils::FilePaths toolSearchPaths() const;

    QtTaskTree::Group autoDetectDeviceToolsRecipe();

    void offerKitCreation();

    void requestToolDetection(const Utils::FilePaths &searchPaths);
    void registerToolDetectionTask(quint64 token);
    void deregisterToolDetectionTask(quint64 token);

    virtual Utils::Result<> supportsBuildingProject(const Utils::FilePath &projectDir) const;

public:
    Utils::BoolAspect allowEmptyCommand{this};
    Utils::StringSelectionAspect linkDevice{this};
    Utils::BoolAspect sshForwardDebugServerPort{this};
    Utils::PortListAspect freePortsAspect{this};

protected:
    IDevice();

    virtual void fromMap(const Utils::Store &map);
    virtual void toMap(Utils::Store &map) const;
    virtual void postLoad() {}

    using OpenTerminal = std::function<void(const Utils::Environment &,
                                            const Utils::FilePath &,
                                            const Utils::Continuation<> &)>;
    void setOpenTerminal(const OpenTerminal &openTerminal);
    void setDisplayType(const QString &type);
    void setOsType(Utils::OsType osType);
    void setFileAccess(Utils::DeviceFileAccessPtr fileAccess, bool announce = true);
    void setFileAccessFactory(std::function<Utils::DeviceFileAccessPtr()> fileAccessFactory);

    virtual void initDeviceToolAspects();

private:
    IDevice(const IDevice &) = delete;
    IDevice &operator=(const IDevice &) = delete;

    int version() const;
    void setFromSdk();
    bool kitCreationEnabled() const;

    const std::unique_ptr<Internal::IDevicePrivate> d;
    friend class DeviceManager;
    friend class IDeviceFactory;
};

class PROJECTEXPLORER_EXPORT DeviceConstRef
{
public:
    DeviceConstRef(const IDevice::ConstPtr &device);
    DeviceConstRef(const IDevice::Ptr &device);
    virtual ~DeviceConstRef();

    IDevice::ConstPtr lock() const;

    Utils::Id id() const;
    QString displayName() const;
    SshParameters sshParameters() const;
    Utils::FilePath filePath(const QString &pathOnDevice) const;
    QVariant extraData(Utils::Id kind) const;
    Utils::Id linkDeviceId() const;

private:
    std::weak_ptr<const IDevice> m_constDevice;
};

class PROJECTEXPLORER_EXPORT DeviceRef : public DeviceConstRef
{
public:
    DeviceRef(const IDevice::Ptr &device);

    IDevice::Ptr lock() const;

    void setDisplayName(const QString &displayName);
    void setSshParameters(const SshParameters &params);

private:
    std::weak_ptr<IDevice> m_mutableDevice;
};

class PROJECTEXPLORER_EXPORT DeviceTester : public QObject
{
    Q_OBJECT

public:
    enum TestResult { TestSuccess, TestFailure };

    virtual void testDevice() = 0;
    virtual void stopTest() = 0;

signals:
    void progressMessage(const QString &message);
    void errorMessage(const QString &message);
    void finished(ProjectExplorer::DeviceTester::TestResult result);

protected:
    explicit DeviceTester(const IDevice::Ptr &device, QObject *parent = nullptr);
    ~DeviceTester() override;
    const IDevice::Ptr &device() const { return m_device; }

private:
    const IDevice::Ptr m_device;
};

} // namespace ProjectExplorer
