var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/saasDevice/devicePlanning/modules/deviceConnections/components/DeviceConnectionsPanel.tsx
var DeviceConnectionsPanel_exports = {};
__export(DeviceConnectionsPanel_exports, {
  default: () => DeviceConnectionsPanel_default
});
module.exports = __toCommonJS(DeviceConnectionsPanel_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_materials = require("@pisell/materials");
var import_icons = require("@ant-design/icons");
var import_model = require("../../../model");
var import_shared = require("../../../shared");
var import_ConnectExistingDeviceModal = __toESM(require("./ConnectExistingDeviceModal"));
var import_ConnectionDeviceCard = __toESM(require("./ConnectionDeviceCard"));
var import_ConnectedDevicePreviewModal = __toESM(require("./ConnectedDevicePreviewModal"));
var import_DeviceConnectionsPanel = require("./DeviceConnectionsPanel.less");
var DeviceConnectionsPanel = ({
  activeKind,
  connectionType,
  isBuildIns,
  hideConnectButton,
  readonly,
  currentDevice,
  connections,
  loading,
  submitting,
  deleting,
  deletingDevice,
  getText,
  translation,
  onCreateConnection,
  onUpdateConnection,
  onDeleteConnection,
  onEditDevice,
  onDeleteDevice
}) => {
  const [removingConnection, setRemovingConnection] = (0, import_react.useState)();
  const [connectMode, setConnectMode] = (0, import_react.useState)();
  const [editingConnection, setEditingConnection] = (0, import_react.useState)();
  const [previewConnection, setPreviewConnection] = (0, import_react.useState)();
  if (activeKind === "integrated") {
    return null;
  }
  const isSmart = activeKind === "smart";
  const getConnectedDevice = (connection) => (isSmart ? connection.target_device : connection.source_device) || null;
  const getConnectedDeviceName = (connection) => {
    if (!connection) return "";
    const device = getConnectedDevice(connection);
    return device ? translation(device.name) || String(device.id) : "-";
  };
  const title = getText(
    isBuildIns ? "pisell2.saas.device-planning.drawer.build-ins" : isSmart ? "pisell2.saas.device-planning.drawer.connections.peripherals" : "pisell2.saas.device-planning.drawer.connections.connected-to"
  );
  const emptyText = getText(
    isBuildIns ? "pisell2.saas.device-planning.drawer.build-ins.empty" : isSmart ? "pisell2.saas.device-planning.drawer.connections.no-peripherals" : "pisell2.saas.device-planning.drawer.connections.not-connected-smart"
  );
  const menuItems = [
    {
      key: "connect-existing",
      icon: /* @__PURE__ */ import_react.default.createElement(import_icons.LinkOutlined, null),
      label: getText(
        "pisell2.saas.device-planning.drawer.connections.connect-existing"
      ),
      onClick: () => setConnectMode("existing")
    },
    {
      key: "add-new",
      icon: /* @__PURE__ */ import_react.default.createElement(import_icons.PlusOutlined, null),
      label: getText("pisell2.saas.device-planning.drawer.connections.add-new"),
      onClick: () => setConnectMode("new")
    }
  ];
  const actionItems = (connection) => {
    const device = getConnectedDevice(connection);
    const canManageComponent = isBuildIns && (device == null ? void 0 : device.structure) === "component";
    const items = [];
    if (canManageComponent && device && onEditDevice) {
      items.push({
        key: "edit-device",
        icon: /* @__PURE__ */ import_react.default.createElement(import_icons.EditOutlined, null),
        label: getText("pisell2.saas.device-planning.detail.edit"),
        onClick: () => onEditDevice(device)
      });
    }
    items.push({
      key: "edit",
      icon: /* @__PURE__ */ import_react.default.createElement(import_icons.EditOutlined, null),
      label: getText(
        "pisell2.saas.device-planning.drawer.connections.edit-configuration"
      ),
      onClick: () => setEditingConnection(connection)
    });
    items.push({
      key: "remove",
      icon: /* @__PURE__ */ import_react.default.createElement(import_icons.DeleteOutlined, null),
      danger: true,
      label: getText(
        isBuildIns ? "pisell2.saas.device-planning.action.delete" : "pisell2.saas.device-planning.drawer.connections.remove"
      ),
      onClick: () => {
        if (isBuildIns && device && onDeleteDevice) {
          onDeleteDevice(device);
          return;
        }
        setRemovingConnection(connection);
      },
      disabled: Boolean(isBuildIns && deletingDevice)
    });
    return items;
  };
  const connectButton = isBuildIns ? /* @__PURE__ */ import_react.default.createElement(import_materials.Button, { icon: /* @__PURE__ */ import_react.default.createElement(import_icons.PlusOutlined, null), onClick: () => setConnectMode("new") }, getText("pisell2.saas.device-planning.drawer.build-ins.add")) : isSmart ? /* @__PURE__ */ import_react.default.createElement(
    import_antd.Dropdown,
    {
      menu: { items: menuItems },
      trigger: ["click"],
      placement: "bottomRight"
    },
    /* @__PURE__ */ import_react.default.createElement(import_materials.Button, { icon: /* @__PURE__ */ import_react.default.createElement(import_icons.PlusOutlined, null) }, getText("pisell2.saas.device-planning.drawer.connections.connect"))
  ) : /* @__PURE__ */ import_react.default.createElement(import_materials.Button, { icon: /* @__PURE__ */ import_react.default.createElement(import_icons.PlusOutlined, null), onClick: () => setConnectMode("existing") }, getText("pisell2.saas.device-planning.drawer.connections.connect"));
  const getStatusLabel = (value) => {
    if (!value) return "-";
    const key = `pisell2.saas.device-planning.status.${value}`;
    const text = getText(key);
    return text && text !== key ? text : value;
  };
  const getStatusTone = (value) => {
    if (value === "online" || value === "connected" || value === "linked") {
      return "success";
    }
    if (value === "connecting") return "processing";
    if (value === "unlinked") return "warning";
    if (value === "disconnected") return "error";
    return "default";
  };
  const getDataValue = (data, key) => {
    if (!data) return void 0;
    const value = data[key];
    if (value == null || typeof value === "object") return void 0;
    return String(value);
  };
  const getNetworkLocalIp = (data) => {
    const network = data == null ? void 0 : data.network;
    if (!network || typeof network !== "object" || Array.isArray(network)) {
      return void 0;
    }
    return getDataValue(network, "local_ip");
  };
  const getConnectionLines = (connection) => {
    var _a;
    const connectionType2 = (0, import_shared.getConnectionTypeLabel)(
      (_a = connection.config) == null ? void 0 : _a.connection_type
    );
    const parts = [connectionType2 === "-" ? void 0 : connectionType2];
    const connectionData = connection.data;
    const ip = getDataValue(connectionData, "ip") || getNetworkLocalIp(connectionData);
    const port = getDataValue(connectionData, "port");
    const macAddress = getDataValue(connectionData, "mac");
    if (ip) parts.push(`IP: ${ip}`);
    if (port) parts.push(`Port: ${port}`);
    if (macAddress) parts.push(`MAC: ${macAddress}`);
    return parts.filter(Boolean).length ? [parts.filter(Boolean).join(" · ")] : [];
  };
  const getDeviceStatusLines = (device) => {
    var _a, _b, _c;
    if ((device == null ? void 0 : device.type_kind) !== "smart") return [];
    const ip = ((_a = device.data) == null ? void 0 : _a.ip) || ((_c = (_b = device == null ? void 0 : device.data) == null ? void 0 : _b.network) == null ? void 0 : _c.local_ip);
    return ip ? [`IP: ${ip}`] : [];
  };
  const getDeviceStatuses = (device) => {
    if ((device == null ? void 0 : device.type_kind) === "smart") {
      return [
        {
          key: "link",
          label: getStatusLabel(device.link || "unconnected"),
          tone: getStatusTone(device.link || "unconnected")
        },
        {
          key: "online",
          label: getStatusLabel(device.status || "unknown"),
          tone: getStatusTone(device.status || "unknown")
        }
      ];
    }
    return [
      {
        key: "online",
        label: getStatusLabel((device == null ? void 0 : device.status) || "unknown"),
        tone: getStatusTone((device == null ? void 0 : device.status) || "unknown")
      }
    ];
  };
  const renderConnectionItem = (connection) => {
    var _a, _b, _c, _d, _e, _f;
    const device = getConnectedDevice(connection);
    return /* @__PURE__ */ import_react.default.createElement(
      import_ConnectionDeviceCard.default,
      {
        key: connection.id,
        title: device ? translation(device.name) || device.id : "-",
        deviceInfo: {
          icon: ((_a = device == null ? void 0 : device.type) == null ? void 0 : _a.icon) || (isSmart ? "PrinterOutlined" : "DesktopOutlined"),
          modelName: translation((_b = device == null ? void 0 : device.model) == null ? void 0 : _b.name) || (device == null ? void 0 : device.model_code) || "-",
          brandName: translation((_d = (_c = device == null ? void 0 : device.model) == null ? void 0 : _c.brand) == null ? void 0 : _d.name) || ((_e = device == null ? void 0 : device.model) == null ? void 0 : _e.brand_code) || "-",
          typeName: translation((_f = device == null ? void 0 : device.type) == null ? void 0 : _f.name) || (device == null ? void 0 : device.type_code) || "-",
          statusLines: getDeviceStatusLines(device)
        },
        connectionInfo: {
          lines: getConnectionLines(connection)
        },
        deviceStatuses: getDeviceStatuses(device),
        connectionStatuses: [
          {
            key: "connection",
            label: getStatusLabel(connection.status || "unconnected"),
            tone: getStatusTone(connection.status || "unconnected")
          }
        ],
        profiles: (connection.profiles || []).map((profile) => ({
          key: String(profile.id),
          label: translation(profile.name) || profile.id
        })),
        lastSeen: connection.last_seen ? `${getText("pisell2.saas.device-planning.detail.last-seen")}${connection.last_seen}` : void 0,
        actions: readonly ? void 0 : actionItems(connection),
        showPreview: isSmart,
        onPreview: () => setPreviewConnection(connection)
      }
    );
  };
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "device-detail-drawer__connections" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "device-detail-drawer__connections-header" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "device-detail-drawer__connections-title" }, /* @__PURE__ */ import_react.default.createElement(
    import_materials.Icon,
    {
      type: isBuildIns ? "AppstoreOutlined" : isSmart ? "ApiOutlined" : "LinkOutlined"
    }
  ), /* @__PURE__ */ import_react.default.createElement("span", null, title)), hideConnectButton ? null : connectButton), /* @__PURE__ */ import_react.default.createElement(import_antd.Spin, { spinning: loading }, connections.length ? /* @__PURE__ */ import_react.default.createElement("div", { className: "device-detail-drawer__connection-list" }, connections.map(renderConnectionItem)) : /* @__PURE__ */ import_react.default.createElement("div", { className: "device-detail-drawer__connections-empty" }, /* @__PURE__ */ import_react.default.createElement(
    import_antd.Empty,
    {
      image: import_antd.Empty.PRESENTED_IMAGE_SIMPLE,
      description: emptyText
    }
  ))), removingConnection ? /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellModal,
    {
      open: true,
      title: getText(
        "pisell2.saas.device-planning.drawer.connections.remove-title"
      ),
      onCancel: () => setRemovingConnection(void 0),
      okText: getText(
        "pisell2.saas.device-planning.drawer.connections.remove"
      ),
      cancelText: getText(
        "pisell2.saas.device-planning.drawer.connections.cancel"
      ),
      okButtonProps: {
        block: true,
        size: "large",
        danger: true,
        loading: deleting,
        onClick: async () => {
          await onDeleteConnection(removingConnection.id);
          setRemovingConnection(void 0);
        }
      },
      cancelButtonProps: {
        block: true,
        size: "large",
        type: "default",
        disabled: deleting,
        onClick: () => setRemovingConnection(void 0)
      },
      width: 460,
      headerDivider: false
    },
    (0, import_model.formatToken)(
      getText(
        "pisell2.saas.device-planning.drawer.connections.remove-confirm"
      ),
      { DeviceName: getConnectedDeviceName(removingConnection) }
    )
  ) : null, connectMode ? /* @__PURE__ */ import_react.default.createElement(
    import_ConnectExistingDeviceModal.default,
    {
      open: true,
      mode: connectMode,
      connectionType,
      isBuildIn: isBuildIns,
      targetStructure: isBuildIns ? "component" : void 0,
      currentDevice,
      connectedDeviceIds: connections.map(
        (connection) => activeKind === "smart" ? connection.target_device_id : connection.source_device_id
      ),
      currentWorkAreaId: currentDevice.workarea_id,
      getText,
      translation,
      submitting,
      onClose: () => setConnectMode(void 0),
      onSubmit: async (payload) => {
        await onCreateConnection(payload);
        setConnectMode(void 0);
      }
    }
  ) : null, editingConnection ? /* @__PURE__ */ import_react.default.createElement(
    import_ConnectExistingDeviceModal.default,
    {
      open: true,
      mode: "edit",
      connectionType,
      isBuildIn: isBuildIns,
      currentDevice,
      editConnection: editingConnection,
      connectedDeviceIds: [],
      currentWorkAreaId: currentDevice.workarea_id,
      getText,
      translation,
      submitting,
      onClose: () => setEditingConnection(void 0),
      onUpdate: async (id, payload) => {
        await onUpdateConnection(id, payload);
        setEditingConnection(void 0);
      }
    }
  ) : null, (previewConnection == null ? void 0 : previewConnection.target_device) ? /* @__PURE__ */ import_react.default.createElement(
    import_ConnectedDevicePreviewModal.default,
    {
      open: true,
      device: previewConnection.target_device,
      connectionType,
      getText,
      translation,
      onClose: () => setPreviewConnection(void 0)
    }
  ) : null);
};
var DeviceConnectionsPanel_default = DeviceConnectionsPanel;
