import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _asyncToGenerator } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { markDeviceConnectionConnected, markDeviceConnectionDisconnected } from "../serve.js";
import { PERIPHERAL_TABLE_NAME, buildPeripheralConnectParams, buildTargetDeviceData, createLocalPeripheralBinding, getPhysicalDeviceFromConnection } from "../utils/peripheralRuntime.js";
//#region src/plus/saasDevice/appPeripheral/services/peripheralConnectionService.ts
const getSQLiteAdapter = function() {
	var _ref = _asyncToGenerator(function* (app) {
		return app === null || app === void 0 ? void 0 : app.sqlite;
	});
	return function getSQLiteAdapter(_x) {
		return _ref.apply(this, arguments);
	};
}();
const saveLocalPeripheralBinding = function() {
	var _ref2 = _asyncToGenerator(function* (app, binding) {
		const sqlite = yield getSQLiteAdapter(app);
		if (!(sqlite === null || sqlite === void 0 ? void 0 : sqlite.bulkUpdate)) return;
		yield sqlite.bulkUpdate(PERIPHERAL_TABLE_NAME, [binding]);
	});
	return function saveLocalPeripheralBinding(_x2, _x3) {
		return _ref2.apply(this, arguments);
	};
}();
const getLocalPeripheralBindings = function() {
	var _ref3 = _asyncToGenerator(function* (app) {
		const sqlite = yield getSQLiteAdapter(app);
		if (!(sqlite === null || sqlite === void 0 ? void 0 : sqlite.getAll)) return [];
		const bindings = yield sqlite.getAll(PERIPHERAL_TABLE_NAME);
		return Array.isArray(bindings) ? bindings.filter((binding) => binding === null || binding === void 0 ? void 0 : binding.connection_id) : [];
	});
	return function getLocalPeripheralBindings(_x4) {
		return _ref3.apply(this, arguments);
	};
}();
const deleteLocalPeripheralBindings = function() {
	var _ref4 = _asyncToGenerator(function* (app, ids) {
		if (!ids.length) return;
		const sqlite = yield getSQLiteAdapter(app);
		if (!(sqlite === null || sqlite === void 0 ? void 0 : sqlite.bulkDelete)) return;
		yield sqlite.bulkDelete(PERIPHERAL_TABLE_NAME, ids);
	});
	return function deleteLocalPeripheralBindings(_x5, _x6) {
		return _ref4.apply(this, arguments);
	};
}();
const syncLocalPeripheralBindings = function() {
	var _ref5 = _asyncToGenerator(function* ({ app, connections }) {
		const bindings = yield 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}`);
		}
		yield deleteLocalPeripheralBindings(app, staleBindingIds);
		return keptBindings;
	});
	return function syncLocalPeripheralBindings(_x7) {
		return _ref5.apply(this, arguments);
	};
}();
/**
* Connects one configured device connection to a physical peripheral.
*
* Execution order:
* 1. Calls the native peripheral plugin with either uuid or ip.
* 2. Reports the returned physical device to the connected API via `_target_device.data`.
* 3. Writes a SQLite cache record with physical device info and optional peripheral usage.
*
* @returns The connected physical device and the updated local cache binding.
*/
const connectPeripheralConnection = function() {
	var _ref6 = _asyncToGenerator(function* ({ app, plugin, connection, target, peripheralUsage }) {
		if (!(plugin === null || plugin === void 0 ? void 0 : plugin.connect)) throw new Error("Peripheral plugin is not available.");
		const connectParams = 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 = yield plugin.connect(connectParams);
		const physicalDevice = result === null || result === void 0 ? void 0 : result.data;
		if (!(physicalDevice === null || physicalDevice === void 0 ? void 0 : physicalDevice.is_connect)) throw new Error("Peripheral connect failed.");
		yield markDeviceConnectionConnected(connection.id, { _target_device: { data: buildTargetDeviceData(connection, physicalDevice) } });
		const binding = createLocalPeripheralBinding(connection, physicalDevice, peripheralUsage);
		yield saveLocalPeripheralBinding(app, binding);
		return {
			physicalDevice,
			binding
		};
	});
	return function connectPeripheralConnection(_x8) {
		return _ref6.apply(this, arguments);
	};
}();
const syncPeripheralConnectionStatus = function() {
	var _ref7 = _asyncToGenerator(function* ({ app, connection, physicalDevice, peripheralUsage }) {
		if (physicalDevice.is_connect) yield markDeviceConnectionConnected(connection.id, { _target_device: { data: buildTargetDeviceData(connection, physicalDevice) } });
		else yield markDeviceConnectionDisconnected(connection.id);
		const binding = createLocalPeripheralBinding(connection, physicalDevice, peripheralUsage);
		yield saveLocalPeripheralBinding(app, binding);
		return {
			binding,
			physicalDevice
		};
	});
	return function syncPeripheralConnectionStatus(_x9) {
		return _ref7.apply(this, arguments);
	};
}();
/**
* Disconnects one configured device connection from its physical peripheral.
*
* Execution order:
* 1. Reports disconnected state to the API.
* 2. Writes a SQLite cache record with `is_connect=false`.
* 3. Clears `peripheral_usage`, so label printers must choose usage again next time.
*
* @returns The updated local cache binding.
*/
const disconnectPeripheralConnection = function() {
	var _ref8 = _asyncToGenerator(function* ({ app, connection, physicalDevice }) {
		yield markDeviceConnectionDisconnected(connection.id);
		const nextDevice = physicalDevice ? _objectSpread2(_objectSpread2({}, physicalDevice), {}, {
			is_connect: false,
			status_code: physicalDevice.status_code || "-1"
		}) : void 0;
		const binding = createLocalPeripheralBinding(connection, nextDevice, void 0);
		yield saveLocalPeripheralBinding(app, binding);
		return {
			binding,
			physicalDevice: nextDevice
		};
	});
	return function disconnectPeripheralConnection(_x10) {
		return _ref8.apply(this, arguments);
	};
}();
const updatePeripheralUsage = function() {
	var _ref9 = _asyncToGenerator(function* ({ app, connection, localBinding, physicalDevice, peripheralUsage }) {
		var _nextPhysicalDevice$i;
		const nextPhysicalDevice = physicalDevice || (localBinding === null || localBinding === void 0 ? void 0 : localBinding.physical_device) || getPhysicalDeviceFromConnection(connection);
		const binding = _objectSpread2(_objectSpread2({}, createLocalPeripheralBinding(connection, nextPhysicalDevice, peripheralUsage)), {}, {
			physical_uuid: (nextPhysicalDevice === null || nextPhysicalDevice === void 0 ? void 0 : nextPhysicalDevice.uuid) || (localBinding === null || localBinding === void 0 ? void 0 : localBinding.physical_uuid) || void 0,
			physical_device: nextPhysicalDevice || (localBinding === null || localBinding === void 0 ? void 0 : localBinding.physical_device) || void 0,
			is_connect: Boolean((_nextPhysicalDevice$i = nextPhysicalDevice === null || nextPhysicalDevice === void 0 ? void 0 : nextPhysicalDevice.is_connect) !== null && _nextPhysicalDevice$i !== void 0 ? _nextPhysicalDevice$i : localBinding === null || localBinding === void 0 ? void 0 : localBinding.is_connect)
		});
		yield saveLocalPeripheralBinding(app, binding);
		return {
			binding,
			physicalDevice: nextPhysicalDevice
		};
	});
	return function updatePeripheralUsage(_x11) {
		return _ref9.apply(this, arguments);
	};
}();
//#endregion
export { connectPeripheralConnection, disconnectPeripheralConnection, syncLocalPeripheralBindings, syncPeripheralConnectionStatus, updatePeripheralUsage };
