"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useBleDevicePairing = void 0;
const react_1 = require("react");
const rxjs_1 = require("rxjs");
const operators_1 = require("rxjs/operators");
const errors_1 = require("@ledgerhq/errors");
const deviceAccess_1 = require("../../hw/deviceAccess");
const getVersionUseCase_1 = require("../../device/use-cases/getVersionUseCase");
/**
 * Triggers a BLE pairing with a device
 * @param deviceId A BLE device id
 * @returns An object containing:
 * - isPaired: a boolean set to true if the device has been paired, false otherwise
 * - pairingError: any PairingError that occurred, null otherwise
 *
 * When the device is locked, notify the pairing error and retry
 * until the device is unlocked
 */
const useBleDevicePairing = ({ deviceId, }) => {
    const [isPaired, setIsPaired] = (0, react_1.useState)(false);
    const [pairingError, setPairingError] = (0, react_1.useState)(null);
    (0, react_1.useEffect)(() => {
        const requestObservable = (0, deviceAccess_1.withDevice)(deviceId)(t => (0, rxjs_1.from)((0, getVersionUseCase_1.getVersion)(t))).pipe((0, operators_1.first)(), (0, operators_1.retry)({
            delay: (err) => {
                if (err instanceof errors_1.LockedDeviceError) {
                    setPairingError(err);
                    return (0, rxjs_1.timer)(1000);
                }
                return (0, rxjs_1.throwError)(() => err);
            },
        }));
        const sub = requestObservable.subscribe({
            next: (_value) => {
                setIsPaired(true);
                setPairingError(null);
            },
            error: (error) => {
                setIsPaired(false);
                setPairingError(error);
            },
        });
        return () => {
            sub.unsubscribe();
        };
    }, [deviceId]);
    return { isPaired, pairingError };
};
exports.useBleDevicePairing = useBleDevicePairing;
//# sourceMappingURL=useBleDevicePairing.js.map