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,
  disconnectPeripheralConnection: () => disconnectPeripheralConnection,
  getLocalPeripheralBindings: () => getLocalPeripheralBindings,
  getSQLiteAdapter: () => getSQLiteAdapter,
  saveLocalPeripheralBinding: () => saveLocalPeripheralBinding,
  syncLocalPeripheralBindings: () => syncLocalPeripheralBindings,
  syncPeripheralConnectionStatus: () => syncPeripheralConnectionStatus,
  updatePeripheralUsage: () => updatePeripheralUsage
});
module.exports = __toCommonJS(peripheralConnectionService_exports);
var import_serve = require("../serve");
var import_peripheralRuntime = require("../utils/peripheralRuntime");
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]);
};
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);
};
var syncLocalPeripheralBindings = async ({
  app,
  connections
}) => {
  const bindings = await getLocalPeripheralBindings(app);
  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);
  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.");
  }
  const result = await plugin.connect(connectParams);
  const physicalDevice = result == null ? void 0 : result.data;
  if (!(physicalDevice == null ? void 0 : physicalDevice.is_connect)) {
    throw new Error("Peripheral connect failed.");
  }
  await (0, import_serve.markDeviceConnectionConnected)(connection.id, {
    _target_device: {
      data: (0, import_peripheralRuntime.buildTargetDeviceData)(connection, physicalDevice)
    }
  });
  const binding = (0, import_peripheralRuntime.createLocalPeripheralBinding)(
    connection,
    physicalDevice,
    peripheralUsage
  );
  await saveLocalPeripheralBinding(app, binding);
  return {
    physicalDevice,
    binding
  };
};
var syncPeripheralConnectionStatus = async ({
  app,
  connection,
  physicalDevice,
  peripheralUsage
}) => {
  if (physicalDevice.is_connect) {
    await (0, import_serve.markDeviceConnectionConnected)(connection.id, {
      _target_device: {
        data: (0, import_peripheralRuntime.buildTargetDeviceData)(connection, physicalDevice)
      }
    });
  } else {
    await (0, import_serve.markDeviceConnectionDisconnected)(connection.id);
  }
  const binding = (0, import_peripheralRuntime.createLocalPeripheralBinding)(
    connection,
    physicalDevice,
    peripheralUsage
  );
  await saveLocalPeripheralBinding(app, binding);
  return {
    binding,
    physicalDevice
  };
};
var disconnectPeripheralConnection = async ({
  app,
  connection,
  physicalDevice
}) => {
  await (0, import_serve.markDeviceConnectionDisconnected)(connection.id);
  const nextDevice = physicalDevice ? {
    ...physicalDevice,
    is_connect: false,
    status_code: physicalDevice.status_code || "-1"
  } : void 0;
  const binding = (0, import_peripheralRuntime.createLocalPeripheralBinding)(connection, nextDevice, void 0);
  await saveLocalPeripheralBinding(app, binding);
  return {
    binding,
    physicalDevice: nextDevice
  };
};
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);
  return {
    binding,
    physicalDevice: nextPhysicalDevice
  };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  connectPeripheralConnection,
  disconnectPeripheralConnection,
  getLocalPeripheralBindings,
  getSQLiteAdapter,
  saveLocalPeripheralBinding,
  syncLocalPeripheralBindings,
  syncPeripheralConnectionStatus,
  updatePeripheralUsage
});
