#pragma once

#include <QHash>
#include <memory>
#include <optional>
#include <vector>

#include "device_bus/registry/IDeviceRegistry.h"
#include "device_bus/tree/DeviceTreeModel.h"

namespace softbus::device_bus::registry
{

class DeviceRegistry : public IDeviceRegistry
{
public:
    explicit DeviceRegistry(std::shared_ptr<DeviceTreeModel> treeModel);
    ~DeviceRegistry() override = default;

    void registerDevice(const softbus::devices::DeviceInfo& info) override;
    void unregisterDevice(int id) override;

    std::optional<softbus::devices::DeviceInfo> findById(int id) const override;
    std::vector<softbus::devices::DeviceInfo> listDevices() const override;

    bool upsertFromMonitorEvent(const softbus::device_bus::monitor::DeviceEvent& ev) override;
    bool markOfflineFromMonitorEvent(const softbus::device_bus::monitor::DeviceEvent& ev) override;

private:
    static QString buildStableKey(const softbus::device_bus::monitor::DeviceEvent& ev);
    static QString buildPreferredNodeId(const softbus::device_bus::monitor::DeviceEvent& ev, const QString& stableKey);
    static QString inferType(const softbus::device_bus::monitor::DeviceEvent& ev);
    static QString inferEndpoint(const softbus::device_bus::monitor::DeviceEvent& ev);
    static QString inferName(const softbus::device_bus::monitor::DeviceEvent& ev);
    static QJsonObject buildParams(const softbus::device_bus::monitor::DeviceEvent& ev);

private:
    std::shared_ptr<DeviceTreeModel> m_treeModel;
    QHash<int, softbus::devices::DeviceInfo> m_devicesById;
    QHash<QString, QString> m_stableKeyToNodeId;
};

} // namespace softbus::device_bus::registry

