var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/saasDevice/appPeripheral/services/peripheralConnectionService.ts
var peripheralConnectionService_exports = {};
__export(peripheralConnectionService_exports, {
  connectPeripheralConnection: () => connectPeripheralConnection,
  deleteLocalPeripheralBinding: () => deleteLocalPeripheralBinding,
  getLocalPeripheralBindings: () => getLocalPeripheralBindings,
  getSQLiteAdapter: () => getSQLiteAdapter,
  reconnectPeripheralConnection: () => reconnectPeripheralConnection,
  removePeripheralConnection: () => removePeripheralConnection,
  saveLocalPeripheralBinding: () => saveLocalPeripheralBinding,
  savePeripheralConnectionStatus: () => savePeripheralConnectionStatus,
  syncLocalPeripheralBindings: () => syncLocalPeripheralBindings,
  updatePeripheralUsage: () => updatePeripheralUsage
});
module.exports = __toCommonJS(peripheralConnectionService_exports);
var import_peripheralRuntime = require("../utils/peripheralRuntime");
var addPeripheralLog = (app, title, metadata, type = "info") => {
  var _a, _b;
  (_b = (_a = app == null ? void 0 : app.logger) == null ? void 0 : _a.addLog) == null ? void 0 : _b.call(_a, {
    type,
    title,
    metadata
  });
};
var getSQLiteAdapter = async (app) => {
  return app == null ? void 0 : app.sqlite;
};
var saveLocalPeripheralBinding = async (app, binding) => {
  const sqlite = await getSQLiteAdapter(app);
  if (!(sqlite == null ? void 0 : sqlite.bulkUpdate)) return;
  await sqlite.bulkUpdate(import_peripheralRuntime.PERIPHERAL_TABLE_NAME, [binding]);
  addPeripheralLog(app, "appPeripheral-SQLite保存外设绑定", {
    connectionId: binding.connection_id,
    uuid: binding.physical_uuid,
    isConnect: binding.is_connect,
    usage: binding.peripheral_usage
  });
};
var getLocalPeripheralBindings = async (app) => {
  const sqlite = await getSQLiteAdapter(app);
  if (!(sqlite == null ? void 0 : sqlite.getAll)) return [];
  const bindings = await sqlite.getAll(import_peripheralRuntime.PERIPHERAL_TABLE_NAME);
  return Array.isArray(bindings) ? bindings.filter((binding) => binding == null ? void 0 : binding.connection_id) : [];
};
var deleteLocalPeripheralBindings = async (app, ids) => {
  if (!ids.length) return;
  const sqlite = await getSQLiteAdapter(app);
  if (!(sqlite == null ? void 0 : sqlite.bulkDelete)) return;
  await sqlite.bulkDelete(import_peripheralRuntime.PERIPHERAL_TABLE_NAME, ids);
  addPeripheralLog(app, "appPeripheral-SQLite删除外设绑定", { ids });
};
var deleteLocalPeripheralBinding = async (app, connection) => {
  await deleteLocalPeripheralBindings(app, [`connection_${connection.id}`]);
};
var syncLocalPeripheralBindings = async ({
  app,
  connections
}) => {
  const bindings = await getLocalPeripheralBindings(app);
  addPeripheralLog(app, "appPeripheral-同步本地外设绑定开始", {
    cloudConnectionCount: connections.length,
    localBindingCount: bindings.length
  });
  const cloudConnectionIds = new Set(connections.map((connection) => connection.id));
  const keptBindings = [];
  const staleBindingIds = [];
  for (const binding of bindings) {
    if (cloudConnectionIds.has(Number(binding.connection_id))) {
      keptBindings.push(binding);
      continue;
    }
    staleBindingIds.push(binding.id || `connection_${binding.connection_id}`);
  }
  await deleteLocalPeripheralBindings(app, staleBindingIds);
  addPeripheralLog(app, "appPeripheral-同步本地外设绑定完成", {
    keptBindingCount: keptBindings.length,
    staleBindingIds
  });
  return keptBindings;
};
var connectPeripheralConnection = async ({
  app,
  plugin,
  connection,
  target,
  peripheralUsage
}) => {
  if (!(plugin == null ? void 0 : plugin.connect)) {
    throw new Error("Peripheral plugin is not available.");
  }
  const connectParams = (0, import_peripheralRuntime.buildPeripheralConnectParams)(connection, target);
  if (!connectParams) {
    throw new Error("Peripheral connect requires device identity.");
  }
  if (!connectParams.uuid && !connectParams.ip) {
    throw new Error("Peripheral connect requires uuid or ip.");
  }
  addPeripheralLog(app, "appPeripheral-插件connect开始", {
    connectionId: connection.id,
    connectParams,
    peripheralUsage
  });
  const result = await plugin.connect(connectParams);
  const physicalDevice = result == null ? void 0 : result.data;
  if (!(physicalDevice == null ? void 0 : physicalDevice.is_connect)) {
    addPeripheralLog(
      app,
      "appPeripheral-插件connect失败",
      { connectionId: connection.id, result },
      "error"
    );
    throw new Error("Peripheral connect failed.");
  }
  const binding = (0, import_peripheralRuntime.createLocalPeripheralBinding)(
    connection,
    physicalDevice,
    peripheralUsage
  );
  await saveLocalPeripheralBinding(app, binding);
  addPeripheralLog(app, "appPeripheral-插件connect成功", {
    connectionId: connection.id,
    uuid: physicalDevice.uuid,
    connectType: physicalDevice.connect_type
  });
  return {
    physicalDevice,
    binding
  };
};
var savePeripheralConnectionStatus = async ({
  app,
  connection,
  physicalDevice,
  peripheralUsage
}) => {
  const binding = (0, import_peripheralRuntime.createLocalPeripheralBinding)(
    connection,
    physicalDevice,
    peripheralUsage
  );
  await saveLocalPeripheralBinding(app, binding);
  return {
    binding,
    physicalDevice
  };
};
var reconnectPeripheralConnection = async ({
  app,
  plugin,
  connection,
  physicalDevice,
  peripheralUsage
}) => {
  const uuid = (physicalDevice == null ? void 0 : physicalDevice.uuid) || (0, import_peripheralRuntime.getPeripheralUuid)(connection);
  if (!uuid) {
    throw new Error("Peripheral reconnect requires uuid.");
  }
  addPeripheralLog(app, "appPeripheral-插件reconnect开始", {
    connectionId: connection.id,
    uuid
  });
  const result = (plugin == null ? void 0 : plugin.reconnect) ? await plugin.reconnect({ uuid }) : await (async () => {
    const connectParams = (0, import_peripheralRuntime.buildPeripheralConnectParams)(connection, { uuid });
    if (!(plugin == null ? void 0 : plugin.connect) || !connectParams) {
      throw new Error("Peripheral reconnect is not available.");
    }
    return plugin.connect(connectParams);
  })();
  const nextDevice = result == null ? void 0 : result.data;
  if (!(nextDevice == null ? void 0 : nextDevice.is_connect)) {
    addPeripheralLog(
      app,
      "appPeripheral-插件reconnect失败",
      { connectionId: connection.id, uuid, result },
      "error"
    );
    throw new Error("Peripheral reconnect failed.");
  }
  const binding = (0, import_peripheralRuntime.createLocalPeripheralBinding)(
    connection,
    nextDevice,
    peripheralUsage
  );
  await saveLocalPeripheralBinding(app, binding);
  addPeripheralLog(app, "appPeripheral-插件reconnect成功", {
    connectionId: connection.id,
    uuid: nextDevice.uuid,
    connectType: nextDevice.connect_type
  });
  return {
    binding,
    physicalDevice: nextDevice
  };
};
var removePeripheralConnection = async ({
  app,
  plugin,
  connection,
  physicalDevice
}) => {
  const uuid = (physicalDevice == null ? void 0 : physicalDevice.uuid) || (0, import_peripheralRuntime.getPeripheralUuid)(connection);
  if (uuid && (plugin == null ? void 0 : plugin.remove)) {
    addPeripheralLog(app, "appPeripheral-插件remove开始", {
      connectionId: connection.id,
      uuid
    });
    await plugin.remove({ uuid });
    addPeripheralLog(app, "appPeripheral-插件remove完成", {
      connectionId: connection.id,
      uuid
    });
  }
  await deleteLocalPeripheralBinding(app, connection);
};
var updatePeripheralUsage = async ({
  app,
  connection,
  localBinding,
  physicalDevice,
  peripheralUsage
}) => {
  const nextPhysicalDevice = physicalDevice || (localBinding == null ? void 0 : localBinding.physical_device) || (0, import_peripheralRuntime.getPhysicalDeviceFromConnection)(connection);
  const binding = {
    ...(0, import_peripheralRuntime.createLocalPeripheralBinding)(connection, nextPhysicalDevice, peripheralUsage),
    physical_uuid: (nextPhysicalDevice == null ? void 0 : nextPhysicalDevice.uuid) || (localBinding == null ? void 0 : localBinding.physical_uuid) || void 0,
    physical_device: nextPhysicalDevice || (localBinding == null ? void 0 : localBinding.physical_device) || void 0,
    is_connect: Boolean(
      (nextPhysicalDevice == null ? void 0 : nextPhysicalDevice.is_connect) ?? (localBinding == null ? void 0 : localBinding.is_connect)
    )
  };
  await saveLocalPeripheralBinding(app, binding);
  addPeripheralLog(app, "appPeripheral-更新打印机角色完成", {
    connectionId: connection.id,
    uuid: binding.physical_uuid,
    peripheralUsage
  });
  return {
    binding,
    physicalDevice: nextPhysicalDevice
  };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  connectPeripheralConnection,
  deleteLocalPeripheralBinding,
  getLocalPeripheralBindings,
  getSQLiteAdapter,
  reconnectPeripheralConnection,
  removePeripheralConnection,
  saveLocalPeripheralBinding,
  savePeripheralConnectionStatus,
  syncLocalPeripheralBindings,
  updatePeripheralUsage
});
