#include "devices/DeviceTypes.h"

namespace softbus::devices {

DeviceKind kindFromType(const QString &typeStr) {
  // 使用静态 QHash，仅在首次调用时初始化一次，后续调用直接极速查表
  static const QHash<QString, DeviceKind> typeMap = {
      {QStringLiteral("serial"), DeviceKind::Serial},
      {QStringLiteral("can"), DeviceKind::Can},
      {QStringLiteral("ethernet"), DeviceKind::Network},
      {QStringLiteral("network"), DeviceKind::Network},
      {QStringLiteral("virtual"), DeviceKind::Virtual},
      {QStringLiteral("distributed"), DeviceKind::Distributed}};

  // value() 方法在找不到键时，会返回传入的第二个默认参数
  return typeMap.value(typeStr.trimmed().toLower(), DeviceKind::Unknown);
}

DeviceKind inferDeviceKindFromEndpoint(const QString &endpoint) {
  const QString ep = endpoint.trimmed();
  // 使用结构体数组来存储设备类型和前缀的映射
  struct Rule {
    const QString prefix;
    DeviceKind kind;
  };

  static const Rule rules[] = {
      {QStringLiteral("/dev/tty"), DeviceKind::Serial},
      {QStringLiteral("can"), DeviceKind::Can},
      {QStringLiteral("tcp://"), DeviceKind::Tcp},
      {QStringLiteral("udp://"), DeviceKind::Udp}
      // 未来在这里添加其他设备类型
  };

  // 遍历规则表进行前缀匹配
  for (const auto &rule : rules) {
    if (ep.startsWith(rule.prefix)) {
      return rule.kind;
    }
  }

  return DeviceKind::Unknown;
}

QString driverKeyFor(DeviceKind kind) {
  switch (kind) {
  case DeviceKind::Serial:
    return QStringLiteral("serial_qt");
  case DeviceKind::Can:
    return QStringLiteral("can_socketcan");
  case DeviceKind::Tcp:
    return QStringLiteral("tcp_qt");
  case DeviceKind::Udp:
    return QStringLiteral("udp_qt");
  case DeviceKind::Network:
    return QStringLiteral("network_qt");
  case DeviceKind::Virtual:
    return QStringLiteral("virtual_device");
  case DeviceKind::Distributed:
    return QStringLiteral("distributed_node");
  default:
    return QStringLiteral("unknown");
  }
}

} // namespace softbus::devices
