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/hooks/usePeripheralRuntime.ts
var usePeripheralRuntime_exports = {};
__export(usePeripheralRuntime_exports, {
  usePeripheralRuntime: () => usePeripheralRuntime
});
module.exports = __toCommonJS(usePeripheralRuntime_exports);
var import_react = require("react");
var import_ahooks = require("ahooks");
var import_materials = require("@pisell/materials");
var import_peripheralConnectionService = require("../services/peripheralConnectionService");
var import_peripheralRuntime = require("../utils/peripheralRuntime");
var usePeripheralRuntime = ({
  row,
  getAppInstance,
  getText,
  onPhysicalChange,
  onUsageChange
}) => {
  const [actionLoading, setActionLoading] = (0, import_react.useState)(false);
  const rowRef = (0, import_react.useRef)(row);
  const getPeripheralPlugin = (0, import_ahooks.useMemoizedFn)(
    () => {
      var _a, _b;
      return (_b = (_a = getAppInstance()) == null ? void 0 : _a.getPlugin) == null ? void 0 : _b.call(_a, "peripheral");
    }
  );
  const addRuntimeLog = (0, import_ahooks.useMemoizedFn)(
    (title, metadata, type = "info") => {
      var _a, _b, _c;
      (_c = (_b = (_a = getAppInstance()) == null ? void 0 : _a.logger) == null ? void 0 : _b.addLog) == null ? void 0 : _c.call(_b, {
        type,
        title,
        metadata
      });
    }
  );
  const applyBinding = (0, import_ahooks.useMemoizedFn)(
    (nextRow, binding) => {
      onPhysicalChange(nextRow.id, binding.physical_device);
      onUsageChange(nextRow.id, binding.peripheral_usage);
    }
  );
  const getKnownPhysicalDevice = (0, import_ahooks.useMemoizedFn)(
    (targetRow) => targetRow.physical
  );
  const showConnectFailed = (0, import_ahooks.useMemoizedFn)((silent, error) => {
    var _a;
    if (silent) return;
    const nativeMessage = error instanceof Error && error.message ? error.message : "";
    const connectType = (0, import_peripheralRuntime.normalizeConnectType)((_a = rowRef.current.connection.config) == null ? void 0 : _a.connection_type);
    const messageKey = connectType === "USB" ? "pisell2.saas.app-peripheral.connect-failed.usb" : connectType === "BLUETOOTH" ? "pisell2.saas.app-peripheral.connect-failed.bluetooth" : connectType === "ETHERNET" || connectType === "WIFI" ? "pisell2.saas.app-peripheral.connect-failed.network" : "pisell2.saas.app-peripheral.connect-failed";
    (0, import_materials.PisellToast)({
      content: nativeMessage || getText(messageKey),
      duration: 2
    });
  });
  const saveConnectedPhysicalDevice = (0, import_ahooks.useMemoizedFn)(
    async (targetRow, physicalDevice, peripheralUsage) => {
      const result = await (0, import_peripheralConnectionService.savePeripheralConnectionStatus)({
        app: getAppInstance(),
        connection: targetRow.connection,
        physicalDevice,
        peripheralUsage
      });
      applyBinding(targetRow, result.binding);
      addRuntimeLog("appPeripheral-保存已连接候选", {
        connectionId: targetRow.id,
        uuid: physicalDevice.uuid
      });
      return result;
    }
  );
  const saveDisconnectedPhysicalDevice = (0, import_ahooks.useMemoizedFn)(
    async (targetRow, physicalDevice) => {
      var _a;
      const nextPhysicalDevice = {
        ...physicalDevice,
        uuid: physicalDevice.uuid || "",
        is_connect: false,
        name: "name" in physicalDevice && physicalDevice.name ? physicalDevice.name : String(targetRow.peripheralId),
        connect_type: "connect_type" in physicalDevice && physicalDevice.connect_type || (0, import_peripheralRuntime.normalizeConnectType)((_a = targetRow.connection.config) == null ? void 0 : _a.connection_type) || "ETHERNET",
        status_code: "status_code" in physicalDevice && physicalDevice.status_code || "-1"
      };
      const result = await (0, import_peripheralConnectionService.savePeripheralConnectionStatus)({
        app: getAppInstance(),
        connection: targetRow.connection,
        physicalDevice: nextPhysicalDevice,
        peripheralUsage: targetRow.usage
      });
      applyBinding(targetRow, result.binding);
      return result;
    }
  );
  const connectPhysicalDevice = (0, import_ahooks.useMemoizedFn)(
    async (targetRow, physicalDevice, peripheralUsage, options = {}) => {
      addRuntimeLog("appPeripheral-connect触发", {
        connectionId: targetRow.id,
        target: physicalDevice,
        peripheralUsage,
        silent: options.silent
      });
      try {
        const nextUsage = peripheralUsage ?? ((0, import_peripheralRuntime.isLabelPrinterConnection)(targetRow.connection) ? rowRef.current.usage : void 0);
        const result = await (0, import_peripheralConnectionService.connectPeripheralConnection)({
          app: getAppInstance(),
          plugin: getPeripheralPlugin(),
          connection: targetRow.connection,
          target: physicalDevice,
          peripheralUsage: nextUsage
        });
        applyBinding(targetRow, result.binding);
        if (!options.silent) {
          (0, import_materials.PisellToast)({
            content: getText("pisell2.saas.app-peripheral.connect-success"),
            duration: 2
          });
        }
        addRuntimeLog("appPeripheral-connect成功", {
          connectionId: targetRow.id,
          uuid: result.physicalDevice.uuid
        });
        return result;
      } catch (e) {
        addRuntimeLog(
          "appPeripheral-connect失败",
          {
            connectionId: targetRow.id,
            target: physicalDevice,
            error: e
          },
          "error"
        );
        throw e;
      }
    }
  );
  const connectKnownPhysicalDevice = (0, import_ahooks.useMemoizedFn)(
    async (targetRow, options = {}) => {
      try {
        const knownPhysicalDevice = getKnownPhysicalDevice(targetRow);
        if (knownPhysicalDevice == null ? void 0 : knownPhysicalDevice.uuid) {
          return await connectPhysicalDevice(
            targetRow,
            knownPhysicalDevice,
            void 0,
            options
          );
        }
        const ip = (0, import_peripheralRuntime.getManualConnectionIp)(targetRow.connection);
        if (!ip) {
          throw new Error("Peripheral connect requires selected device or manual IP.");
        }
        const manualTarget = { ip };
        try {
          return await connectPhysicalDevice(targetRow, manualTarget, void 0, options);
        } catch (e) {
          await saveDisconnectedPhysicalDevice(targetRow, manualTarget);
          throw e;
        }
      } catch (e) {
        showConnectFailed(options == null ? void 0 : options.silent, e);
        throw e;
      }
    }
  );
  const connectSelectedPhysicalDevice = (0, import_ahooks.useMemoizedFn)(
    async (targetRow, physicalDevice) => {
      if (physicalDevice.is_connect) {
        return saveConnectedPhysicalDevice(targetRow, physicalDevice);
      }
      try {
        return await connectPhysicalDevice(targetRow, physicalDevice);
      } catch (e) {
        await saveDisconnectedPhysicalDevice(targetRow, physicalDevice);
        showConnectFailed(false, e);
        throw e;
      }
    }
  );
  const handleUpdatePeripheralUsage = (0, import_ahooks.useMemoizedFn)(
    async (targetRow, usage) => {
      const physicalDevice = getKnownPhysicalDevice(targetRow);
      addRuntimeLog("appPeripheral-更新打印机角色触发", {
        connectionId: targetRow.id,
        usage,
        uuid: physicalDevice == null ? void 0 : physicalDevice.uuid
      });
      setActionLoading(true);
      try {
        const result = await (0, import_peripheralConnectionService.updatePeripheralUsage)({
          app: getAppInstance(),
          connection: targetRow.connection,
          physicalDevice,
          peripheralUsage: usage
        });
        applyBinding(targetRow, result.binding);
        (0, import_materials.PisellToast)({
          content: getText("pisell2.saas.app-peripheral.save-success"),
          duration: 2
        });
      } catch (e) {
        (0, import_materials.PisellToast)({
          content: getText("pisell2.saas.app-peripheral.connect-failed"),
          duration: 2
        });
        addRuntimeLog(
          "appPeripheral-更新打印机角色失败",
          {
            connectionId: targetRow.id,
            usage,
            error: e
          },
          "error"
        );
      } finally {
        setActionLoading(false);
      }
    }
  );
  const handleRemovePeripheral = (0, import_ahooks.useMemoizedFn)(
    async (targetRow) => {
      var _a;
      addRuntimeLog("appPeripheral-忽略连接插件清理触发", {
        connectionId: targetRow.id,
        uuid: ((_a = getKnownPhysicalDevice(targetRow)) == null ? void 0 : _a.uuid) || (0, import_peripheralRuntime.getPeripheralUuid)(targetRow.connection)
      });
      await (0, import_peripheralConnectionService.removePeripheralConnection)({
        app: getAppInstance(),
        plugin: getPeripheralPlugin(),
        connection: targetRow.connection,
        physicalDevice: getKnownPhysicalDevice(targetRow)
      });
    }
  );
  (0, import_react.useEffect)(() => {
    rowRef.current = row;
  }, [row]);
  return {
    isRuntimeSubmitting: actionLoading,
    connectKnownPhysicalDevice,
    handleRemovePeripheral,
    handleUpdatePeripheralUsage,
    connectSelectedPhysicalDevice,
    saveConnectedPhysicalDevice
  };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  usePeripheralRuntime
});
